1 JavaConfig  配置方法

之前我们都是在xml文件中定义bean的,比如:

1
2
3
4
5
6
7
8
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  
    <bean id="helloBean" class="com.mkyong.hello.impl.HelloWorldImpl">
  
</beans>

其实我们可以使用注解来完成这些事情,例如下面的代码,完成的功能和上面的xml配置的功能是一样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mkyong.hello.HelloWorld;
import com.mkyong.hello.impl.HelloWorldImpl;
  
@Configuration
public class AppConfig {
  
    @Bean(name="helloBean")
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }
  
}

 想象一个场景,我们有一个很大的工程项目,如果将所有的bean都配置在一个xml文件中,那么这个文件就会非常的大。所以在很多的时候我们都会将一个大的xml配置文件分割为好几份。这样方便管理,最后在总的那个xml文件中导入就行了,比如:

1
2
3
4
5
6
7
8
9
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  
    <import resource="config/customer.xml"/>
        <import resource="config/scheduler.xml"/>
  
</beans>

 但是现在我们也可以使用JavaConfig来完成同样的工作了:

1
2
3
4
5
6
7
8
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
  
@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {
  
}

  我们对这个例子来看一个demo:

CustomerBo.java

1
2
3
4
5
6
7
8
public class CustomerBo {
  
    public void printMsg(String msg) {
  
        System.out.println("CustomerBo : " + msg);
    }
  
}

 SchedulerBo.java

1
2
3
4
5
6
7
8
public class SchedulerBo {
  
    public void printMsg(String msg) {
  
        System.out.println("SchedulerBo : " + msg);
    }
  
}

  现在我们来使用注解:

1
2
3
4
5
6
7
8
9
10
@Configuration
public class CustomerConfig {
  
    @Bean(name="customer")
    public CustomerBo customerBo(){
  
        return new CustomerBo();
  
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
@Configuration
public class SchedulerConfig {
  
    @Bean(name="scheduler")
    public SchedulerBo suchedulerBo(){
  
        return new SchedulerBo();
  
    }
  
}

  AppConfig.java

1
2
3
4
5
6
7
8
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
  
@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {
  
}

  然后运行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class App {
    public static void main(String[] args) {
  
        ApplicationContext context = new AnnotationConfigApplicationContext(
                AppConfig.class);
  
        CustomerBo customer = (CustomerBo) context.getBean("customer");
        customer.printMsg("Hello 1");
  
        SchedulerBo scheduler = (SchedulerBo) context.getBean("scheduler");
        scheduler.printMsg("Hello 2");
  
    }
}

  

2  set注入方法 构造器注入也是很类似

我们编写spring 框架的代码时候。一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量。并且要配套写上 get 和 set方法。

Boss 拥有 Office 和 Car 类型的两个属性:   
  
  
清单 3. Boss.Java

  1. package com.baobaotao;
  2. public class Boss {
  3. private Car car;
  4. private Office office;
  5. // 省略 get/setter
  6. @Override
  7. public String toString() {
  8. return "car:" + car + "/n" + "office:" + office;
  9. }
  10. }

System.out.println必须实现toString方法
  
我们在 Spring 容器中将 Office 和 Car 声明为 Bean,并注入到 Boss Bean 中:下面是使用传统 XML 完成这个工作的配置文件 beans.xml:   
  
  
清单 4. beans.xml 将以上三个类配置成 Bean

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  6. <bean id="boss" class="com.baobaotao.Boss">
  7. <property name="car" ref="car"/>
  8. <property name="office" ref="office" />
  9. </bean>
  10. <bean id="office" class="com.baobaotao.Office">
  11. <property name="officeNo" value="002"/>
  12. </bean>
  13. <bean id="car" class="com.baobaotao.Car" scope="singleton">
  14. <property name="brand" value=" 红旗 CA72"/>
  15. <property name="price" value="2000"/>
  16. </bean>
  17. </beans>

当我们运行以下代码时,控制台将正确打出 boss 的信息:   
  
  
清单 5. 测试类:AnnoIoCTest.java

  1. import org.springframework.context.ApplicationContext;
  2. import org.springframework.context.support.ClassPathXmlApplicationContext;
  3. public class AnnoIoCTest {
  4. public static void main(String[] args) {
  5. String[] locations = {"beans.xml"};
  6. ApplicationContext ctx =
  7. new ClassPathXmlApplicationContext(locations);
  8. Boss boss = (Boss) ctx.getBean("boss");
  9. System.out.println(boss);
  10. }
  11. }

这说明 Spring 容器已经正确完成了 Bean 创建和装配的工作。

3   @Autowired 自动注入 

Spring 2.5 引入了 @Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。 通过 @Autowired的使用来消除 set ,get方法。

要实现我们要精简程序的目的。需要这样来处理:

* 在applicationContext.xml中加入:

Spring 通过一个 BeanPostProcessor 对 @Autowired 进行解析,所以要让 @Autowired 起作用必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。

* 修改在原来注入spirng容器中的bean的方法。 
     在域变量上加上标签@Autowired,并且去掉 相应的get 和set方法

清单 6. 使用 @Autowired 注释的 Boss.java

package com.baobaotao;
import org.springframework.beans.factory.annotation.Autowired; public class Boss { @Autowired
private Car car; @Autowired
private Office office; …
}

* 在applicatonContext.xml中 把原来 引用的<porpery >标签也去掉。

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/> <!-- 移除 boss Bean 的属性注入配置的信息 -->
<bean id="boss" class="com.baobaotao.Boss"/> <bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value=""/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value=""/>
</bean>
</beans>

这样,当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。   
  
按照上面的配置,Spring 将直接采用 Java 反射机制对 Boss 中的 car 和 office 这两个私有成员变量进行自动注入。所以对成员变量使用 @Autowired 后,您大可将它们的 setter 方法(setCar() 和 setOffice())从 Boss 中删除。   
  
当然,您也可以通过 @Autowired 对方法或构造函数进行标注,如果构造函数有两个入参,分别是 bean1 和 bean2,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 CountryService (Bean1 bean1 ,Bean2 bean2) 的入参来创建 CountryService Bean。来看下面的代码:  对方法

这时,@Autowired 将查找被标注的方法的入参类型的 Bean,并调用方法自动注入这些 Bean。而下面的使用方法则对构造函数进行标注:

由于 Boss() 构造函数有两个入参,分别是 car 和 office,@Autowired 将分别寻找和它们类型匹配的 Bean,将它们作为 Boss(Car car ,Office office) 的入参来创建 Boss Bean。

 

转载自  http://www.cnblogs.com/rollenholt/archive/2012/12/27/2835087.html

http://blog.csdn.net/heyutao007/article/details/5981555

使用Spring的JavaConfig 和 @Autowired注解与自动装配的更多相关文章

  1. Spring中@Autowired注解与自动装配

    1 使用配置文件的方法来完成自动装配我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. ...

  2. Spring@Autowired注解与自动装配

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  3. 【转】Spring@Autowired注解与自动装配

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  4. Spring@Autowired注解与自动装配(转发)

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  5. [转] Spring@Autowired注解与自动装配

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  6. Spring学习记录(十一)---使用注解和自动装配

    Spring支持用注解配置Bean,更简便. 上面的组件,是根据实际情况配的.比如写的一个类,是做业务处理的,那就用注解@Service表示服务层组件,以此类推.将整体分成不同部分. 要在xml加入c ...

  7. 搭建SSH框架整合Struts2和Spring时,使用@Autowired注解无法自动注入

    © 版权声明:本文为博主原创文章,转载请注明出处 1.问题描述: 搭建SSH框架,在进行Struts2和Spring整合时,使用Spring的@Autowired自动注入失败,运行报错java.lan ...

  8. Spring自动装配----注解装配----Spring自带的@Autowired注解

    Spring自动装配----注解装配----Spring自带的@Autowired注解 父类 package cn.ychx; public interface Person { public voi ...

  9. spring boot 中@Autowired注解无法自动注入的错误

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/huihuilovei/article/de ...

随机推荐

  1. JavaWeb(六)Listener监听器

    监听器 监听器就是一个实现特定接口的普通java程序,这个程序专门用于监听另一个java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行. Servlet监听器 在Se ...

  2. javaweb中重定向和请求转发(response.sendRedirect()和request.getRequestDispatcher(rul).forward(request,response)))的区别

    先来两张图,方便理解: 可以看出,重定向时,是服务器向游览器重新发送了一个response命令,让游览器再次向url2发送请求,以获取url2的资源 而请求转发时,类似于是服务器自己向自己发了一个跳转 ...

  3. Ta-lib函数功能列表

    import tkinter as tk from tkinter import ttk import matplotlib.pyplot as plt import numpy as np impo ...

  4. java web方面的面试问题,Spring MVC方面的面试问题,摘自java web轻量级开发面试教程

    本文摘自java web轻量级开发面试教程: https://baike.baidu.com/item/Java%20Web%E8%BD%BB%E9%87%8F%E7%BA%A7%E5%BC%80%E ...

  5. Java的static关键字

    本文参考:Java的static关键字 通过static关键字可以满足两方面的需要.一种情形是,只想为某特定域分配单一存储空间,而不去考虑究竟要创建多少对象,甚至根本就不创建任何对象.另一种情形是,希 ...

  6. 面试技巧,如何通过索引说数据库优化能力,内容来自Java web轻量级开发面试教程

    上星期写了一个篇文章,数据库方面的面试技巧,如何从建表方面展示自己能力,承蒙管理员抬举,放入首页,也承蒙各位厚爱,两天内收获了将近770个点击,也一度进入48小时热榜. 为了感谢管理员和大家的支持,再 ...

  7. C / C++ 运行环境搭建教程

    C / C++ 运行环境搭建教程 一.实验环境 本机操作系统:Windows 7 64位 虚拟机:VMware Workstation 12 pro 虚拟机操作系统:Linux CentOS 7 二. ...

  8. Html5笔记之第六天

    Canvas元素 <canvas> 标签定义图形,比如图表和其他图像,您必须使用脚本来绘制图形. 在画布上(Canvas)画一个红色矩形,渐变矩形,彩色矩形,和一些彩色的文字. <c ...

  9. Centos7.2部署.Net Core2.0 WebApi

    部署前准备 1.VisualStudio2017+.netcore2.0SDK 2.Centos7.2 3.SecureCRT,Xftp(根据自己喜好) 创建WebApi项目 修改Program.cs ...

  10. Redis基本数据类型

    -------------------Redis基本数据类型------------------- 1.String 字符串     1.概念         1.String 是redis最基本的类 ...