假设 bean 在这里注册。
@Configuration
public class configuration{
@Bean(name = "MyClass")
public MyClass getMyClass(@Value("avalue") final String s){
return new MyClass(s);
}
}
}
并且该类在内部实例化了另一个类,如下所示(两者都不需要注释?)
public class MyClass{
MyOtherClass myOtherClass;
public MyClass(String s){
this.myOtherClass = new MyOtherClass(s);
}
}
public class MyOtherClass{
String s;
public MyOtherClass(String s){
this.s = s;
}
}
这个机制是如何工作的?在 bean 注入中实例化新实例是否安全?这样做有什么好处或坏处?
如果我们也通过将 MyOtherClass 设为 bean 来避免使用它,这会是这样吗?(主要关注:@Autowired 和 getMyclass() 是在正确的位置还是多余的?)
@Configuration
public class configuration{
@Bean(name = "MyOtherClass")
public MyOtherClass getMyOtherClass(@Value("avalue") final String s){
return new MyOtherClass(s);
}
}
@Bean(name = "MyClass")
public MyClass getMyClass(MyClass myClass){
//I was told the input should be myClass not myOtherClass,
//and the return is myClass not new MyClass(myOtherClass);
//since it's already autowired. Is that correct?
//What if the configuration.java and MyClass.java are in different project?
return myClass;
}
}
}
@Component
public class MyClass{
MyOtherClass myOtherClass;
@Autowired
public MyClass(MyOtherClass myOtherClass){
this.myOtherClass = myOtherClass;
}
}
public class MyOtherClass{
String s;
public MyOtherClass(String s){
this.s = s;
}
}