使用注解构造IOC、替代传统的applicationContext.xml配置<bean/>和<property/>传统的spring要在applicationContext.xml中配置:①<bean>类 ②<property>属性 如果有100个类和若干个属性,那么我们就要写成百上千个<bean>、<property>,这种就不利于维护,使用注解就能够解决这个问题。(项目中的方法也可以使用注解来替代)在使用类注解前要在applicationContext.xml文件中添加:<context:component-scan base-package="news"></context:component-scan>注意:base-package可以指定一个包也可指定多个包,多个包逗号隔开使用了<context:component-scan/>之后就可以把<context:annotation-config/>移除,因为<context:component-scan/>也能实现扫描包路径。
1.(类)@Controller
@Controller是对应控制层的<bean>,也就是action类用法:1 @Controller2 @Scope("prototype")3 public class NewsAction extends ActionSupport{4 ……5 }注意:如果@Controller不指定其value【@Controller】,则默认的bean名字为这个类的类名首字母小写,如果指定value【@Controller(value="UserAction")】或者【@Controller("UserAction")】,则使用value作为bean的名字。2、(类)@ Service
@Service对应的是业务层Bean用法:1 @Service("NewsService")2 public class NewsServiceImpl implements NewsService {3 ………4 }3、(类)@ Repository
@Repository对应数据访问层Bean,部分技术人员也喜欢叫dao类用法1 @Repository(value="NewsDao")2 public class NewsDaoImpl extends NewsDaoImpl {3 ………4 }注意:以上三种(@Controller、@Service、@Repository)是针对不同层的类所使用的注解,下面的是针对属性所使用的注解:4.(属性)@ Autowired (不推荐使用,建议使用@Resource)
@Qualifier("...")
用法(在实现类中封装一个属性并私有化,在属性上面添加@Autowired @Qualifier)如下:public class NewsDaoImpl implements NewsDao { //这种方式是spring注解
@Autowired
@Qualifier("mySessionFactory")private SessionFactory sf;} 注意:加入@Qualifier是为了让spring准确地知道要注入的对象,括号里自定义属性名字5.(属性)@Resource(jdk)
用法:public class NewsDaoImpl implements NewsDao {@Resource(name="mySessionFactory")private SessionFactory sf;}通过@Resource注解来给属性sf注入一个名字为mySessionFactory的值Spring中如何配置Hibernate事务 http://www.linuxidc.com/Linux/2013-12/93681.htmStruts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm基于 Spring 设计并实现 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htmSpring-3.2.4 + Quartz-2.2.0集成实例 http://www.linuxidc.com/Linux/2013-10/91524.htm使用 Spring 进行单元测试 http://www.linuxidc.com/Linux/2013-09/89913.htm运用Spring注解实现Netty服务器端UDP应用程序 http://www.linuxidc.com/Linux/2013-09/89780.htmSpring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码 http://www.linuxidc.com/Linux/2013-10/91357.htmSpring 的详细介绍:请点这里
Spring 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-11/137195.htm