我对使用其他项目生成的bean有疑问。更详细:
我有一个项目A如下
public A {
public void print()
{
System.out.println("Hello World");
}
}
配置类如下
@Configuration
public class AConfig {
@Bean
public A a()
{
A bean = new A();
return A;
}
}
现在我有了一个新项目B,其课程如下
public B {
A a;
public setA()
{
this.a = a;
}
public static void main(String[] args)
{
System.out.println(a.print());
}
}
B的配置类如下
@Configuration
@Import(AConfig.class)
public BConfig
{
@Bean
public B b()
{
B bean = new B();
**b.setA(a());-----------------This is not correct. How can i get Instance of class A NOw????**
}
}
谢谢
答案 0 :(得分:4)
@Configuration
类如果bean紧密耦合,只需将它们放在同一个类中:
@Configuration
public class AConfig {
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
B b = new B();
b.setA(a());
return b;
}
}
@Configuration
类 @Configuration
类只是Spring中bean的一个特例:
@Configuration
public class BConfig {
@Autowired
private AConfig aConfig;
@Bean
public B b() {
B b = new B();
b.setA(aConfig.a());
return b;
}
}
@Configuration
类@Configuration
@Import(AConfig.class)
public class BConfig {
@Autowired
private A a;
@Bean
public B b() {
B b = new B();
b.setA(a);
return b;
}
}