IOC装配Bean(注解方式)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOC装配Bean(注解方式)相关的知识,希望对你有一定的参考价值。

Spring的注解装配Bean
Spring2.5 引入使用注解去定义Bean
@Component  描述Spring框架中Bean 
Spring的框架中提供了与@Component注解等效的三个注解:
@Repository 用于对DAO实现类进行标注
@Service 用于对Service实现类进行标注
@Controller 用于对Controller实现类进行标注
***** 三个注解为了后续版本进行增强的.

Bean的属性注入:

普通属性;
@Value(value="itcast")
    private String info;

对象属性:
@Autowired:自动装配默认使用类型注入.
@Autowired
@Qualifier("userDao")       --- 按名称进行注入.

@Autowired
@Qualifier("userDao")       
private UserDao userDao;
等价于
@Resource(name="userDao")
private UserDao userDao;

Bean其他的属性的配置:

配置Bean初始化方法和销毁方法:
* init-method 和 destroy-method.
@PostConstruct 初始化
@PreDestroy  销毁

配置Bean的作用范围:
@Scope

以下是测试案例:

<!-- 扫描多个目录方法两种
    第一种:<context:component-scan base-package="cn.spring.demo1,cn.spring.demo2" />
    第二种:<context:component-scan base-package="cn.spring" />
-->
    <context:component-scan base-package="cn.spring" />

UserService.java

package cn.spring.demo1;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

/*
 * 注解的方式装配bean
 */
//在spring配置文件中<bean id="userservice" class="cn.spring.demo1.UserService">
//@Component("userservice")
@Service("userservice")
//scope默认是单实例 
@Scope(value="prototype")
public class UserService {
    @Value(value="测试1")
    private String info;
    //按类型注入的话@Autowired(required=false 忽略异常)
    //@Autowired(required=true)
    //按名称注入的话加@Qualifier("userdaoonly") 要跟userdao里面的@Repository("userdaoonly")一样(第二种)
    //@Qualifier("userdaoonly")
    //@[email protected][email protected]("userdaoonly")
    @Resource(name="userdaoonly")
    private UserDao userdao;

    public void sayHello(){
        System.out.println("Hello spring Annotation..."+info+userdao);
    }

/*  @Override
    public String toString() {
        return "UserService [info=" + info + ", userdao=" + userdao + "]";
    }*/

    @PostConstruct
    public void setup(){
        System.out.println("初始化……");
    }

    @PreDestroy
    public void teardwon(){
        System.out.println("销毁……");
    }
}

--------------------------------------------------------------------------------------------------------------------------------------------

UserDao.java
package cn.spring.demo1;

import org.springframework.stereotype.Repository;

@Repository("userdaoonly")
public class UserDao {

}
-------------------------------------------------------------------------------------------------------------------------------------
package cn.spring.demo1;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//注解的方式
public class SpringTest1 {
    @Test
    public void demo1() {
        ClassPathXmlApplicationContext applicationcontext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        UserService userservice = (UserService) applicationcontext
                .getBean("userservice");
        //      userservice.sayHello();
        System.out.println(userservice);
        UserService userservice2 = (UserService) applicationcontext
        .getBean("userservice");
        //userservice.sayHello();
        System.out.println(userservice2);
        applicationcontext.close();
    }
}

Spring3.0提供使用Java类定义Bean信息的方法

@Configuration
public class BeanConfig {

    @Bean(name="car")
    public Car showCar(){
        Car car = new Car();
        car.setName("长安");
        car.setPrice(40000d);
        return car;
    }

    @Bean(name="product")
    public Product initProduct(){
        Product product = new Product();
        product.setName("空调");
        product.setPrice(3000d);
        return product;
    }
}

以下是测试案例:

//这个是java类定义bean信息的方式;
package cn.spring.demo2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {

    @Bean(name="car")
    public Car showCar() {
        Car car = new Car();
        car.setName("长安");
        car.setPrice(123.00);
        return car;
    }

    @Bean(name="product")
    public Product showProduct() {
        Product product = new Product();
        product.setName("空调");
        product.setPrice(1234.00);
        return product;
    }
}
-----------------------------------------------------------------------------------------------------------------

package cn.spring.demo2;

public class Car {
    private String name;
    private Double price;

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [name=" + name + ", price=" + price + "]";
    }

}

-----------------------------------------------------------------------------------------------------------------

package cn.spring.demo2;

public class Product {
    private String name;
    private Double price;

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product [name=" + name + ", price=" + price + "]";
    }

}

-----------------------------------------------------------------------------------------------------------------

package cn.spring.demo2;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.spring.demo1.UserService;

public class SpringTest {
    @Test
    public void demo1() {
        ClassPathXmlApplicationContext applicationcontext = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        Car car = (Car) applicationcontext
                .getBean("car");
        Product product = (Product) applicationcontext
                .getBean("product");

        System.out.println(car);
        System.out.println(product);
    }
}

实际开发中使用XML还是注解?

XML:
* bean管理
注解;
* 注入属性的时候比较方便.

两种方式结合;一般使用XML注册Bean,使用注解进行属性的注入.

<context:annotation-config/>
@Autowired
@Qualifier("orderDao")
private OrderDao orderDao;

最后一个整合一下,一个使用XML注册bean一个用注释bean

    <context:annotation-config/>

    <bean id="customerdao" class="cn.spring.demo3.CustomerDao"></bean>

      <bean id="orderdao" class="cn.spring.demo3.OrderDao"></bean>

    <bean id="customerservice" class="cn.spring.demo3.CustomerService">
        <property name="customerdao" ref="customerdao"></property>
        <!--  <property name="orderdao" ref="orderdao"></property>-->
    </bean>
package cn.spring.demo3;

public class CustomerDao {

}
-------------------------------------------
package cn.spring.demo3;

public class OrderDao {

}
--------------------------------------------
package cn.spring.demo3;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class CustomerService {

    private CustomerDao customerdao;

    @Autowired
    @Qualifier("orderdao")
    private OrderDao orderdao;

    public void setCustomerdao(CustomerDao customerdao) {
        this.customerdao = customerdao;
    }

    @Override
    public String toString() {
        return "CustomerService [customerdao=" + customerdao + ", orderdao="
                + orderdao + "]";
    }
}
-----------------------------------------------
测试类写法
package cn.spring.demo3;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    @Test
    public void demo1() {
        ClassPathXmlApplicationContext applicationcontext = new ClassPathXmlApplicationContext(
                "applicationContext2.xml");

        CustomerService customerservice = (CustomerService) applicationcontext
                .getBean("customerservice");
        System.out.println(customerservice);
    }

}

以上是关于IOC装配Bean(注解方式)的主要内容,如果未能解决你的问题,请参考以下文章

在学习spring-IoC容器装配Bean_基于注解配置方式的时候,碰见的两个异常

Spring学习bean装配详解之 通过注解装配 Bean基础配置方式

(转)java之Spring(IOC)注解装配Bean详解

Spring---ioc自动装配和使用注解

Spring之IOC-注解方式

spring5:IOC 操作 Bean 管理(基于注解方式)