@zhuanxu
2017-11-15T16:56:01.000000Z
字数 2663
阅读 1737
JavaEE开发的颠覆者SpringBoot实战
第一个注释是 @Required
,其用法如下:
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Required
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
@Required
的含义是让容器在初始化的就检查Bean的属性需要被注入,防止在运行时抛出NullPointerException
异常。
先看下定义:
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.
*/
boolean required() default true;
}
保留到运行时,然后可以放在基本所有的类型上。运行时IoC容器会根据注释自动注入依赖。
此处如果我们使用@Autowired
注释,可能带来的问题是会有多个候选者,这个时候我们可以通过@Primary
指定到底使用哪个。
public class MovieRecommender {
@Autowired
private MovieCatalog movieCatalog;
// ...
}
xml配置:
<bean class="example.SimpleMovieCatalog" primary="true">
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<!-- inject any dependencies required by this bean -->
</bean>
<bean id="movieRecommender" class="example.MovieRecommender"/>
</beans>
当我们需要对@Autowired
进行更精细的控制的时候,就可以使用@Qualifier
了,相比较于@Primary
能够对Bean进行更精细的控制,看例子:
public class MovieRecommender {
private MovieCatalog movieCatalog;
private CustomerPreferenceDao customerPreferenceDao;
@Autowired
public void prepare(@Qualifier("main")MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
@Qualifier
能够修饰方法和参数,上面的例子是修饰的参数,再来看xml中的配置。
<bean class="example.SimpleMovieCatalog">
<qualifier value="main"/>
<!-- inject any dependencies required by this bean -->
</bean>
<bean class="example.SimpleMovieCatalog">
<qualifier value="action"/>
<!-- inject any dependencies required by this bean -->
</bean>
<bean id="movieRecommender" class="example.MovieRecommender"/>
@Qualifier
除了修饰函数和参数外,还能修饰注释本省,看例子:
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MovieQualifier {
String genre();
Format format();
}
然后代码中的注释:
public class MovieRecommender {
@Autowired
@MovieQualifier(format=Format.VHS, genre="Action")
private MovieCatalog actionVhsCatalog;
@Autowired
@MovieQualifier(format=Format.VHS, genre="Comedy")
private MovieCatalog comedyVhsCatalog;
@Autowired
@MovieQualifier(format=Format.DVD, genre="Action")
private MovieCatalog actionDvdCatalog;
@Autowired
@MovieQualifier(format=Format.BLURAY, genre="Comedy")
private MovieCatalog comedyBluRayCatalog;
// ...
}
这个是JSR-250的标准,里面可以声明Bean的名字,如果不声明,则默认取属性名或者方法名,看例子:
public class SimpleMovieLister {
private MovieFinder movieFinder;
//@Resource(name="movieFinder")
@Resource
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}