Spring注解注入
1、古老的注入方式:
实现类:
/** * @title UserServiceImpl.java * @description UserService实现类 * @author cao_xhu * @version * @create_date Oct 30, 2009 * @copyright (c) CVIC SE */public class UserServiceImpl implements UserService {private UserDAO userDAO;public void setUserDAO(UserDAO userDAO) {this.userDAO = userDAO;}...}
<bean id="userDAO" /></property></bean><bean id="userServiceImpl"/></property></bean>
@Autowiredprivate IndustryDao industryDao;...
@Autowiredpublic void setDao(IndustryDao industryDao){super.setDao(industryDao);}
<!-- 使用 <context:annotation-config/> 简化配置Spring 2.1 添加了一个新的 context 的 Schema 命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。 而我们前面所介绍的 AutowiredAnnotationBeanPostProcessor 和 CommonAnnotationBeanPostProcessor 就是处理这些注释元数据的处理器。但是直接在 Spring 配置文件中定义这些 Bean 显得比较笨拙。Spring 为我们提供了一种方便的注册这些 BeanPostProcessor 的方式,这就是 <context:annotation-config/>。 --><context:annotation-config /><bean id="industryDao"/><bean id="industryService"/>
HibernateService hibernateService;@Autowiredpublic void setHibernateService(@Qualifier("core.system.hibernateService")HibernateService hibernateService){this.hibernateService = hibernateService;}
@Autowired(required = false)public void setHibernateService(@Qualifier("core.system.hibernateService")HibernateService hibernateService){this.hibernateService = hibernateService;}
package com.baobaotao;import javax.annotation.Resource;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;public class Boss { @Resource private Car car; @Resource(name = "office") private Office office; @PostConstruct public void postConstruct1(){ System.out.println("postConstruct1"); } @PreDestroy public void preDestroy1(){ System.out.println("preDestroy1"); } …}
package com.baobaotao;import org.springframework.context.support.ClassPathXmlApplicationContext;public class AnnoIoCTest { public static void main(String[] args) { String[] locations = {"beans.xml"}; ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(locations); Boss boss = (Boss) ctx.getBean("boss"); System.out.println(boss); ctx.destroy();// 关闭 Spring 容器,以触发 Bean 销毁方法的执行 }}
@Componentpublic class Woman{ …}
@Componentpublic class Man{ …}
@Component("human")public class Human{ @Autowired private Woman woman; @Autowired private Man man; …}
@Scope("prototype")@Component("human")public class Human{ …}
<?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:component-scan base-package="springlive.learn.component "/></beans>