1.在spring中使用注解时首先需要对bean.xml进行一些配置,我们可以从spring的官方文档中找到这样的配置说明:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:annotation-config/> </beans>
其中绿色字体部分是需要在xml中加入的内容。
2.我们在之前不用注解的时候xml类似于这么写
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="u" class="model.User"></bean>
<bean id="userService" class="service.UserService">
<!--设值注入 -->
<property name="userDao" ref="userDaoImpl" />
</bean>
<bean id="userDaoImpl" class="daoimpl.UserDaoImpl"></bean>
</beans>
需要在UserService中进行配置注入userDao,而如果用注解我们可以省去这一配置而在UserService类中进行注解
//设值注入
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
这里是自动装配的方式进行注解,这样做会告诉容器到xml中找到与UserDao类型相同的bean的配置进行注入,而不虚理会该bean的id是否等于userDao,只要它的class的值
是UserDao或者它的实现类即可。
这里需要注意一点,在UserService类中必须有该类的无参构造器。
3.下下面介绍一下为什么写了<context:annotation-config/>之后就能进行注解了呢?
在官方文档中我们可以找到这样一段解释:
(The implicitly registered post-processors include AutowiredAnnotationBeanPostProcessor
, CommonAnnotationBeanPostProcessor
, PersistenceAnnotationBeanPostProcessor
, as well as the aforementioned RequiredAnnotationBeanPostProcessor
.)
As always, these can be registered as individual bean definitions, but they can also be implicitly registered by including the following tag in an XML-based Spring configuration.
这两句话其中下面一句是在上面的前边出现的,这样写时为了好理解,意思是这些类可以作为独立的bean定义被注册,这些类是指前面一句中提到的AutowiredAnnotationBeanPostProcessor
, CommonAnnotationBeanPostProcessor
, PersistenceAnnotationBeanPostProcessor
, RequiredAnnotationBeanPostProcessor
,但是他们也可以在基于xml的spring配置中在幕后呗注册。
而以上这些被注册过的类的作用就是,找到注解的标签然后到xml找到相关的bean的配置进行注入。