Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

java - retrieve Bean programmatically

@Configuration
public class MyConfig {
    @Bean(name = "myObj")
    public MyObj getMyObj() {
        return new MyObj();
    }
}

I have this MyConfig object with @Configuration Spring annotation. My question is that how I can retrieve the bean programmatically (in a regular class)?

for example, the code snippet looks like this. Thanks in advance.

public class Foo {
    public Foo(){
    // get MyObj bean here
    }
}

public class Var {
    public void varMethod(){
            Foo foo = new Foo();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

public class Foo {
    public Foo(ApplicationContext context){
        context.getBean("myObj")
    }
}

public class Var {
    @Autowired
    ApplicationContext context;
    public void varMethod(){
            Foo foo = new Foo(context);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...