spring 有两种方式注入,一种是构造方法注入,一种是setter方法注入。这里我们介绍的是setter方法注入
完成setter方法注入是在容器调用无参构造方法后调用setter方法完成注入
官网例子:
public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a setter method so that the Spring container can inject a MovieFinder public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually uses the injected MovieFinder is omitted... }
如何选择注入方式问题
当你不知道选择什么方式注入时,可以考虑两种方式的优缺点。
构造方法:优点,强制你注入,在使用的时候不需要担心是否为空。缺点:构造参数太多,会看起来很不好看,不美观
setteer方式注入:优点:注入完后,可以再次注入。缺点:使用的时候需要注意是否为null,所以在使用setter方法时,最好给个默认值。
还有一点,如果使用第三方的框架时,使用的类没有setter方法,那么只能使用构造方法进行注入了。
思考问题:如果不是通过构造方法返回实例,应该怎么注入呢?例如下面的例子
public class ExampleBean { // a private constructor private ExampleBean(...) { ... } // a static factory method; the arguments to this method can be // considered the dependencies of the bean that is returned, // regardless of how those arguments are actually used. public static ExampleBean createInstance ( AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) { ExampleBean eb = new ExampleBean (...); // some other operations... return eb; } }