IOC容器装配Bean(注解方式)

IOC容器装配Bean(注解方式) 

1.使用注解方式进行Bean注册 

    xml 方式: <bean id="" class=""> 

spring2.5版本 提供一组注解,完成Bean注册 

    * @Component 描述Spring框架中Bean 

导入jar 和 xml方式开发是相同的 

第一步 编写Class,在声明上 添加 @Component 

  1. /**
  2. * 使用Spring2.5注解 注册Bean
  3. */
  4. @Component("helloService")
    // <bean id="helloService" class="...." />
    public class HelloService{
        public void sayHello(){
            System.out.println("hello, spring annotation!");
        }
    }

第二步 编写applicationContext.xml 通知Spring注解类所在包 

需要引入 context 名称空间 

  1. <?xml version="1.0" encoding="UTF-8"?>
    <beansxmlns="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.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置 注解Bean 所在包 -->
    <context:annotation-config/>
    <context:component-scanbase-package="cn.itcast.spring.a_beandefinition"></context:component-scan>
    </beans>
进行测试:
  1. publicclassSpringTest{
  2. @Test
  3. // 测试 注解Bean 注册
  4. public void demo1(){
        ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");
        //bean的名称来自@Component("helloService")
        HelloService helloService =(HelloService) applicationContext.getBean("helloService");
        helloService.sayHello();
    }
spring2.5 引入@Component 等效三个衍生注解 

* @Repository 用于对DAO实现类进行标注 (持久层)

* @Service 用于对Service实现类进行标注 (业务层)

* @Controller 用于对Controller实现类进行标注 (表现层)

 

2.属性依赖注入 

1) 简单属性的注入 通过 @Value注解完成,不需要提供setter方法

  1. @Service("userService")
    public class UserService {
        // 注入name属性
        @Value("itcast")
        private String name;
    }

2) 复杂属性注入,通过@Autowired注解 完成Bean自动装配 

@Autowired 默认按照类型进行注入 

  1. /**
    * 用户操作数据层
    */
    @Repository("userDAO")
    publicclassUserDAO{
    }
  1. /**
    * 用户业务层
    */
    @Service("userService")
    public class UserService{
    // 注入name属性
    @Value("itcast")
    // 简单属性
    privateString name;
     
    //@Autowired默认按照类型
    @Autowired
    private UserDAO userDAO;
    @Override
    public String toString(){
        return "UserService [name="+ name +", userDAO="+ userDAO +"]";
    }
@Value @Autowired注解都可以修饰 成员变量 或者 setter方法,如果修饰成员变量,不需要提供setter方法

 

@Autowired注解 结合 @Qualifer注解按照名称注入

  1. @Service("userService")
    public class UserService {
        @Autowired
        @Qualifier("uDAO")
        // 复杂对象
        private UserDAO userDAO;
    }
@Qualifier("userDAO")注解的名称必须与@Repository("userDAO")名称一致,就会报错!
@Repository("uDAO")
public class UserDAO { 
}

3) 使用@Resource注解 完成复杂对象Bean装配 @Resource@Autowired注解功能相似

  1. @Autowired
  2. @Qualifer("userDAO")
  3. private UserDAO userDAO ; 
等价于 
  1. @Resource(name="userDAO")
  2. private UserDAO userDAO ;
 

3.Bean其它属性设置 

1) 指定Bean的初始化方法和销毁方法(注解)  <bean init-method="" destroy-method="" />

@PostConstruct  作用 init-method

@PreDestroy  作用 destroy-method 

  1. @Component("lifeBean")
    public class LifeCycleBean{
        @PostConstruct
        public void setup(){
           System.out.println("初始化...");
        }
    @PreDestroy public void teardown(){ System.out.println(
    "销毁..."); }
    }
进行测试:
  1. @Test
    // 测试初始化和销毁
    publicvoid demo1(){
        ClassPathXmlApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");
        LifeCycleBean lifeCycleBean =(LifeCycleBean) applicationContext.getBean("lifeBean");
        System.out.println(lifeCycleBean);
        // 销毁方法执行,必须销毁ApplicationContext
        applicationContext.close();
    }

2) Bean的作用范围  <bean scope="" /> 

@Scope 注解 ,默认作用域 singleton 单例 

  1. @Component("scopeBean")
    // 如果没有指定scope 是 singleton 单例
    @Scope("prototype")
    public class ScopeBean{
    }
进行测试:
  1. @Test
    // 测试Bean 范围
    publicvoid demo2(){
    ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");
    ScopeBean scopeBean =(ScopeBean) applicationContext.getBean("scopeBean");
    System.out.println(scopeBean);
    ScopeBean scopeBean2 =(ScopeBean) applicationContext.getBean("scopeBean");
    System.out.println(scopeBean2);
    }

 

4.Spring3.0 提供 注册Bean的注解

@Configuration 指定POJO类为Spring提供Bean定义信息

@Bean 提供一个Bean定义信息

 

先定义2个JavaBean:

  1. // 轿车
    public class Car{
    private String name;
    private double price;
    public String getName(){
    return name;
    }
    public void setName(String name){
       this.name = name;
    }
    public double getPrice(){
        return price;
    }
    public void setPrice(double price){
        this.price = price;
    }
    @Override
    publicString toString(){
       return "Car [name="+ name +", price="+ price +"]";
    }
    }
    // 商品
    public class Product{
    private String pname;
    private int pnum;
    public String getPname(){
    return pname;
    }
    public void setPname(String pname){
    this.pname = pname;
    }
    publicint getPnum(){
    return pnum;
    }
    public void setPnum(int pnum){
    this.pnum = pnum;
    }
    @Override
    public String toString(){
    return"Product [pname="+ pname +", pnum="+ pnum +"]";
    }
    }
此类需要我们自己编写,好比一个大的工厂。
  1. /**
    * 配置Bean (工厂)
    */
    @Configuration
    public class BeanConfig{
    // 提供两个方法 获得Car和Product对象
    @Bean(name ="car")
    //方法名称随意
    public Car initCar(){
    Car car =newCar();
    car.setName("大众");
    car.setPrice(10000);
    return car;
    }
    @Bean(name ="product")
    public Product showProduct(){
    Product product = new Product();
    product.setPname("空调");
    product.setPnum(100);
    return product;
    }
    }
进行测试:
  1. @Test
    // 获得配置Bean 工厂创建Bean对象
    public void demo(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Car car =(Car) applicationContext.getBean("car");
    System.out.println(car);
    Product product =(Product) applicationContext.getBean("product");
    System.out.println(product);
    }
使用配置BeanSpring扫描到,就可以了

 

5.xml和注解混合使用 

很多企业开发者 还是采用xml作为主流配置 

* Bean 注册 通过XML完成

注入使用 @Autowired 注解完成 

 将2个Dao注入到Service

  1. // 客户DAO
    public class CustomerDAO{
    }
     
    // 订单DAO
    public class OrderDAO{
    }
    Service类(注入):
    // 客户Service
    public class CustomerService{
    // xml注入
    private CustomerDAO customerDAO;
    public void setCustomerDAO(CustomerDAO customerDAO){
    this.customerDAO = customerDAO;
    }
    @Override
    public String toString(){
    return "CustomerService [orderDAO="+ orderDAO +", customerDAO="+ customerDAO +"]";
    }
    }
 
配置(注册):
  1. <bean id="customerDAO"class="cn.itcast.spring.e_xmluseannotaion.CustomerDAO"></bean>
    <bean id="orderDAO" class="cn.itcast.spring.e_xmluseannotaion.OrderDAO"></bean>
    <!--将DAO 注入Service-->
    <bean id="customerService"class="cn.itcast.spring.e_xmluseannotaion.CustomerService">
    <property name="customerDAO" ref="customerDAO"></property>
    </bean>
测试:
  1. @Test
    // 完成 DAO 注入到Service测试
    public void demo(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext2.xml");
    CustomerService customerService =(CustomerService) applicationContext.getBean("customerService");
    System.out.println(customerService);
    }
***************************************************************************************************************************************
此时,我们发现,在注册的时候使用xml比较方便,而在注入的时候使用xml方式比较麻烦,需要提供setter方法,下面使用注解方式注入
  1. // 客户Service
    public class CustomerService{
    // 注解注入
    @Autowired
    private OrderDAO orderDAO;
    // xml注入
    private CustomerDAO customerDAO;
    public void setCustomerDAO(CustomerDAO customerDAO){
    this.customerDAO = customerDAO;
    }
    @Override
    public String toString(){
    return "CustomerService [orderDAO="+ orderDAO +", customerDAO="+ customerDAO +"]";
    }
    }

    <context:annotation-config/> 启用四个注解 使@Resource@ PostConstruct@ PreDestroy@Autowired注解生效

 

结论 :

   1、 xml配置 和 注解配置 效果完全相同 

   2、 如果Bean 来自第三方(源码无法改动), 必须使用xml   

   3、 Spring3.0 Bean注册方式, 使用比较少,主要用于Bean 构造逻辑及其复杂

 

博采众长才能相互印证,故步自封必将粗陋浅薄!
原文地址:https://www.cnblogs.com/tangwan/p/4674974.html