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")
  5. // <bean id="helloService" class="...." />
  6. publicclassHelloService{
  7. publicvoid sayHello(){
  8. System.out.println("hello, spring annotation!");
  9. }
  10. }
 

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

* 需要引入 context 名称空间

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

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

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

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

2.属性依赖注入

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

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

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

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

  1. /**
  2. * 用户操作数据层
  3. */
  4. @Repository("userDAO")
  5. publicclassUserDAO{
  6. }
 
  1. /**
  2. * 用户业务层
  3. */
  4. @Service("userService")
  5. publicclassUserService{
  6. // 注入name属性
  7. @Value("itcast")
  8. // 简单属性
  9. privateString name;
  10.  
  11. //@Autowired默认按照类型
  12. @Autowired
  13. privateUserDAO userDAO;
  14. @Override
  15. publicString toString(){
  16. return"UserService [name="+ name +", userDAO="+ userDAO +"]";
  17. }
  18. }
@Value @Autowired注解都可以修饰 成员变量 或者 setter方法,如果修饰成员变量,不需要提供setter方法

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

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

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")
  2. publicclassLifeCycleBean{
  3. @PostConstruct
  4. publicvoid setup(){
  5. System.out.println("初始化...");
  6. }
  7. @PreDestroy
  8. publicvoid teardown(){
  9. System.out.println("销毁...");
  10. }
  11. }
进行测试:
  1. @Test
  2. // 测试初始化和销毁
  3. publicvoid demo1(){
  4.     ClassPathXmlApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");
  5.     LifeCycleBean lifeCycleBean =(LifeCycleBean) applicationContext.getBean("lifeBean");
  6.     System.out.println(lifeCycleBean);
  7.     // 销毁方法执行,必须销毁ApplicationContext
  8.     applicationContext.close();
  9. }
 

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

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

  1. @Component("scopeBean")
  2. // 如果没有指定scope 是 singleton 单例
  3. @Scope("prototype")
  4. publicclassScopeBean{
  5. }
进行测试:
  1. @Test
  2. // 测试Bean 范围
  3. publicvoid demo2(){
  4. ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");
  5. ScopeBean scopeBean =(ScopeBean) applicationContext.getBean("scopeBean");
  6. System.out.println(scopeBean);
  7. ScopeBean scopeBean2 =(ScopeBean) applicationContext.getBean("scopeBean");
  8. System.out.println(scopeBean2);
  9. }
 

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

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

@Bean 提供一个Bean定义信息

先定义2个JavaBean:

  1. // 轿车
  2. publicclassCar{
  3. privateString name;
  4. privatedouble price;
  5. publicString getName(){
  6. return name;
  7. }
  8. publicvoid setName(String name){
  9. this.name = name;
  10. }
  11. publicdouble getPrice(){
  12. return price;
  13. }
  14. publicvoid setPrice(double price){
  15. this.price = price;
  16. }
  17. @Override
  18. publicString toString(){
  19. return"Car [name="+ name +", price="+ price +"]";
  20. }
  21. }
 
  1. // 商品
  2. publicclassProduct{
  3. privateString pname;
  4. privateint pnum;
  5. publicString getPname(){
  6. return pname;
  7. }
  8. publicvoid setPname(String pname){
  9. this.pname = pname;
  10. }
  11. publicint getPnum(){
  12. return pnum;
  13. }
  14. publicvoid setPnum(int pnum){
  15. this.pnum = pnum;
  16. }
  17. @Override
  18. publicString toString(){
  19. return"Product [pname="+ pname +", pnum="+ pnum +"]";
  20. }
  21. }
此类需要我们自己编写,好比一个大的工厂。
  1. /**
  2. * 配置Bean (工厂)
  3. */
  4. @Configuration
  5. publicclassBeanConfig{
  6. // 提供两个方法 获得Car和Product对象
  7. @Bean(name ="car")
  8. //方法名称随意
  9. publicCar initCar(){
  10. Car car =newCar();
  11. car.setName("大众");
  12. car.setPrice(10000);
  13. return car;
  14. }
  15. @Bean(name ="product")
  16. publicProduct showProduct(){
  17. Product product =newProduct();
  18. product.setPname("空调");
  19. product.setPnum(100);
  20. return product;
  21. }
  22. }
进行测试:
  1. @Test
  2. // 获得配置Bean 工厂创建Bean对象
  3. publicvoid demo(){
  4. ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");
  5. Car car =(Car) applicationContext.getBean("car");
  6. System.out.println(car);
  7. Product product =(Product) applicationContext.getBean("product");
  8. System.out.println(product);
  9. }
使用配置Bean被Spring扫描到,就可以了

5.xml和注解混合使用

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

* Bean 注册 通过XML完成

* 注入使用 @Autowired 注解完成

将2个Dao注入到Service

  1. // 客户DAO
  2. publicclassCustomerDAO{
  3. }
 
  1. // 订单DAO
  2. publicclassOrderDAO{
  3. }
Service类(注入):
  1. // 客户Service
  2. publicclassCustomerService{
  3. // xml注入
  4. privateCustomerDAO customerDAO;
  5. publicvoid setCustomerDAO(CustomerDAO customerDAO){
  6. this.customerDAO = customerDAO;
  7. }
  8. @Override
  9. publicString toString(){
  10. return"CustomerService [orderDAO="+ orderDAO +", customerDAO="
  11. + customerDAO +"]";
  12. }
  13. }
配置(注册):
  1. <bean id="customerDAO"class="cn.itcast.spring.e_xmluseannotaion.CustomerDAO"></bean>
  2. <bean id="orderDAO" class="cn.itcast.spring.e_xmluseannotaion.OrderDAO"></bean>
  3. <!--将DAO 注入Service-->
  4. <bean id="customerService"class="cn.itcast.spring.e_xmluseannotaion.CustomerService">
  5. <property name="customerDAO" ref="customerDAO"></property>
  6. </bean>
测试:
  1. @Test
  2. // 完成 DAO 注入到Service测试
  3. publicvoid demo(){
  4. ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext2.xml");
  5. CustomerService customerService =(CustomerService) applicationContext.getBean("customerService");
  6. System.out.println(customerService);
  7. }
***************************************************************************************************************************************
此时,我们发现,在注册的时候使用xml比较方便,而在注入的时候使用xml方式比较麻烦,需要提供setter方法,下面使用注解方式注入
  1. // 客户Service
  2. publicclassCustomerService{
  3. // 注解注入
  4. @Autowired
  5. privateOrderDAO orderDAO;
  6. // xml注入
  7. privateCustomerDAO customerDAO;
  8. publicvoid setCustomerDAO(CustomerDAO customerDAO){
  9. this.customerDAO = customerDAO;
  10. }
  11. @Override
  12. publicString toString(){
  13. return"CustomerService [orderDAO="+ orderDAO +", customerDAO="
  14. + customerDAO +"]";
  15. }
  16. }
 

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

结论 :

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

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

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

05_IOC容器装配Bean(注解方式)的更多相关文章

  1. 04_IOC容器装配Bean(xml方式)

    IOC容器装配Bean(xml方式) 1.Spring 提供配置Bean三种实例化方式 1)使用类构造器实例化(默认无参数) <bean id="bean1" class=& ...

  2. Spring框架(3)---IOC装配Bean(注解方式)

    IOC装配Bean(注解方式) 上面一遍文章讲了通过xml来装配Bean,那么这篇来讲注解方式来讲装配Bean对象 注解方式需要在原先的基础上重新配置环境: (1)Component标签举例 1:导入 ...

  3. spring IOC装配Bean(注解方式)

    1 Spring的注解装配Bean (1) Spring2.5 引入使用注解去定义Bean @Component 描述Spring框架中Bean (2) Spring的框架中提供了与@Componen ...

  4. Spring 框架 详解 (四)------IOC装配Bean(注解方式)

    Spring的注解装配Bean Spring2.5 引入使用注解去定义Bean @Component  描述Spring框架中Bean Spring的框架中提供了与@Component注解等效的三个注 ...

  5. Spring IOC 一——容器装配Bean的简单使用

    下文:SpringIOC 二-- 容器 和 Bean的深入理解 写在前面 这篇文章去年写的,缘起于去年某段时间被领导临时"抓壮丁"般的叫过去做java开发,然后在网上找了一个 Sp ...

  6. spring IOC容器实例化Bean的方式与RequestContextListener应用

    spring IOC容器实例化Bean的方式有: singleton 在spring IOC容器中仅存在一个Bean实例,Bean以单实例的方式存在. prototype 每次从容器中调用Bean时, ...

  7. Spring容器装配Bean的三种方式

    欢迎查看Java开发之上帝之眼系列教程,如果您正在为Java后端庞大的体系所困扰,如果您正在为各种繁出不穷的技术和各种框架所迷茫,那么本系列文章将带您窥探Java庞大的体系.本系列教程希望您能站在上帝 ...

  8. Spring容器、BeanFactory和ApplicationContext,及3种装配Bean的方式

    目录 一. spring容器理解 二. BeanFactory和ApplicationContext之间的关系 三. BeanFactory详情介绍 四.ApplicationContext介绍 五. ...

  9. spring实战二之Bean的自动装配(非注解方式)

    Bean的自动装配 自动装配(autowiring)有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bea ...

随机推荐

  1. PL/SQL编程基础

    范例:编写不做任何工作的PL/SQL块 BEGIN NULL ; END ; /   范例:编写一个简单的PL/SQL程序 DECLARE v_num NUMBER ; -- 定义一个变量v_num ...

  2. IoC 依赖注入、以及在Spring中的实现

    资源来自网络: 去年火得不行的Spring框架,一般的书籍都会从IoC和AOP开始介绍起,这个IoC概念,个人感觉资料里都写得让人看得有些痛苦,所谓IoC,就是控制反转(Inversion of Co ...

  3. linux设备驱动归纳总结(十二):简单的数码相框【转】

    本文转载自:http://blog.chinaunix.net/uid-25014876-id-116926.html linux设备驱动归纳总结(十二):简单的数码相框 xxxxxxxxxxxxxx ...

  4. Linux Runtime PM介绍【转】

    转自:http://blog.csdn.net/wlwl0071986/article/details/42677403 一.Runtime PM引言 1. 背景 (1)display的需求 (2)系 ...

  5. oralce创建用户

    oralce创建用户: sqlplus /nolog回车 -->conn esun/esun@esuntech; -->create user xlh identified by pass ...

  6. 为Docker容器配置固定IP

    当docker以桥接的方式启动容器时,容器内部的IP是经过DHCP获取的,例如:172.17.0.8/32,且每重启依次IP都会发生变动.某些特殊的情况下,需要容器内有自己固定的一个内部IP.我的实现 ...

  7. Hive与数据库的异同

    一.Hive简介 Hive是基于Hadoop的一个数据仓库工具,可以将结构化的数据文件映射为一张数据库表,并提供完整的sql查询功能,可以将sql语句转换为MapReduce任务进行运行.其优点是学习 ...

  8. JavaEE基础(十九)/异常和File

    1.异常(异常的概述和分类) A:异常的概述 异常就是Java程序在运行过程中出现的错误. B:异常的分类 通过API查看Throwable Error 服务器宕机,数据库崩溃等 Exception ...

  9. [HTML]js实现页面跳转,页面A跳到另一个页面B.以及页面传值(中文)

    要实现从一个页面A跳到另一个页面B,js实现就在A的js代码加跳转代码 JS跳转大概有以下几种方式: 第一种:(跳转到b.html)<script language="javascri ...

  10. 【转】详细讲解Java中log4j的使用方法

    转载地址:http://www.233.com/Java/zhuangye/20070731/142625631.html 1.Log4j是什么? Log4j可以帮助调试(有时候debug是发挥不了作 ...