在Spring3.0及以上版本中,可以使用Annotation替代一部分XML配置,从而简化一些配置代码。
使用此功能前,需要先在头信息中加入允许使用context支持的配置。(这里头信息是在初始创建的applicationContext中,我这里是在application-hibernate,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" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
xsi:schemaLocation="http://www.springframework.org/schema/bean
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
原来的配置信息:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<context:annotation-config></context:annotation-config>
<context:component-scan
base-package="org.liky.ssh.dao.impl,org.liky.ssh.back.service.impl,org.liky.ssh.back.action"></context:component-scan>
@Componentpublic class NewsDAOImpl extends HibernateDaoSupport implements INewsDAO {
@Autowiredpublic NewsDAOImpl(HibernateTemplate hibernateTemplate) {super.setHibernateTemplate(hibernateTemplate);}
•••••@Resource(name="newsDAOImpl")public void setNewsdao(INewsDAO newsdao) {this.newsdao = newsdao;}
@Resource(name = "newsTypeDAOImpl")public void setTypedao(INewsTypeDAO typedao) {this.typedao = typedao;}
这里的Controller也是一个bean,在setService注入的时,resource引用newsService,很好理解的
- <div style="text-align: justify;"><span style="font-size:14px;"><span style="color:#000099;">@Resource(name="newsServiceImpl")</span></span></div>
- <div style="text-align: justify;"><span style="font-size:14px;"><span style="color:#000099;">public void setService(INewsService service) {</span></span></div>
- <div style="text-align: justify;"><span style="font-size:14px;"><span style="color:#000099;">this.service = service;</span></span></div>
- <div style="text-align: justify;"><span style="font-size:14px;"><span style="color:#000099;">}</span></span></div>
总结:Spring的Annotation确实精简了配置文件,它不像hibernate的annotation只是在映射文件体现,