Spring注解Demo

  1. 注入参数值
  2. 采用引用的方式注入集合
  3. 注入表达式
  4. 使用注解声明bean
  5. 使用@Autowired注解
  6. 使用@Resource注解
  7. 使用注解注入表达式

1 注入参数值

1.1 问题

使用Spring创建bean,并且为bean注入各种类型的参数值。

1.2 方案

使用Spring为一个bean注入以下类型的参数值:

1.3 步骤

步骤一:创建项目,导入jar包

创建项目Spring02,导入Spring开发包,如下图:

图-1

步骤二: 创建bean

将Spring01项目中的Computer类复制到当前项目下,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. public class Computer implements Serializable {
  4.     private String mainboard; // 主板
  5.     private String hdd; // 硬盘
  6.     private String ram; // 内存
  7.     public String getMainboard() {
  8.         return mainboard;
  9.     }
  10.     public void setMainboard(String mainboard) {
  11.         this.mainboard = mainboard;
  12.     }
  13.     public String getHdd() {
  14.         return hdd;
  15.     }
  16.     public void setHdd(String hdd) {
  17.         this.hdd = hdd;
  18.     }
  19.     public String getRam() {
  20.         return ram;
  21.     }
  22.     public void setRam(String ram) {
  23.         this.ram = ram;
  24.     }
  25. }

创建一个消息类MessageBean,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. import java.util.Map;
  5. import java.util.Properties;
  6. import java.util.Set;
  7. public class MessageBean implements Serializable {
  8.     // 基本值
  9.     private String name;
  10.     private int age;
  11.     // bean对象
  12.     private Computer computer;
  13.     //集合
  14.     private List<String> langs;
  15.     private Set<String> cities;
  16.     private Map<String, Object> score;
  17.     private Properties props;
  18.     
  19.     public void execute() {
  20.         System.out.println("基本值:");
  21.         System.out.println(name);
  22.         System.out.println(age);
  23.         
  24.         System.out.println("bean对象:");
  25.         if(computer != null) {
  26.             System.out.println(computer.getMainboard());
  27.             System.out.println(computer.getHdd());
  28.             System.out.println(computer.getRam());
  29.         }
  30.         
  31.         System.out.println("编程语言:");
  32.         if(langs != null) {
  33.             for(String lang : langs) {
  34.                 System.out.println(lang);
  35.             }
  36.         }
  37.         
  38.         System.out.println("城市:");
  39.         if(cities != null) {
  40.             for(String city : cities) {
  41.                 System.out.println(city);
  42.             }
  43.         }
  44.         
  45.         System.out.println("分数:");
  46.         if(score != null) {
  47.             Set<String> set = score.keySet();
  48.             for(String key : set) {
  49.                 System.out.println(
  50.                     key + " : " + score.get(key));
  51.             }
  52.         }
  53.         
  54.         System.out.println("参数:");
  55.         if(props != null) {
  56.             Set<Object> propKeySet = props.keySet();
  57.             for(Object key : propKeySet) {
  58.                 System.out.println(
  59.                     key + " : " + props.getProperty(key.toString()));
  60.             }
  61.         }
  62.     }
  63.     public String getName() {
  64.         return name;
  65.     }
  66.     public void setName(String name) {
  67.         this.name = name;
  68.     }
  69.     public int getAge() {
  70.         return age;
  71.     }
  72.     public void setAge(int age) {
  73.         this.age = age;
  74.     }
  75.     public Computer getComputer() {
  76.         return computer;
  77.     }
  78.     public void setComputer(Computer computer) {
  79.         this.computer = computer;
  80.     }
  81.     public List<String> getLangs() {
  82.         return langs;
  83.     }
  84.     public void setLangs(List<String> langs) {
  85.         this.langs = langs;
  86.     }
  87.     public Set<String> getCities() {
  88.         return cities;
  89.     }
  90.     public void setCities(Set<String> cities) {
  91.         this.cities = cities;
  92.     }
  93.     public Map<String, Object> getScore() {
  94.         return score;
  95.     }
  96.     public void setScore(Map<String, Object> score) {
  97.         this.score = score;
  98.     }
  99.     public Properties getProps() {
  100.         return props;
  101.     }
  102.     public void setProps(Properties props) {
  103.         this.props = props;
  104.     }
  105. }

步骤三:声明bean

导入applicationContext.xml,在该配置文件中声明这2个bean,并将Computer注入给MessageBean,代码如下:


    
    
  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.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  6.     xmlns:jee="http://www.springframework.org/schema/jee"
  7.     xmlns:tx="http://www.springframework.org/schema/tx"
  8.     xmlns:aop="http://www.springframework.org/schema/aop"
  9.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  10.     xmlns:util="http://www.springframework.org/schema/util"
  11.     xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  12.     xsi:schemaLocation="
  13.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  14.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
  15.         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
  16.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
  17.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  18.         http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
  19.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  20.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  21.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
  22.     
  23.     <bean id="computer" class="com.tarena.bean.Computer">
  24.         <property name="mainboard" value="技嘉"/>
  25.         <property name="hdd" value="希捷"/>
  26.         <property name="ram" value="金士顿"/>
  27.     </bean>    
  28.     
  29.     <!-- 注入参数值 -->
  30.     <bean id="msg" class="com.tarena.bean.MessageBean">
  31.         <property name="name">
  32.             <value>张三</value>
  33.         </property>
  34.         <property name="age" value="25"/>
  35.         <property name="computer" ref="computer"/>
  36.         <property name="langs">
  37.             <list>
  38.                 <value>Java</value>
  39.                 <value>php</value>
  40.                 <value>.net</value>
  41.             </list>
  42.         </property>
  43.         <property name="cities">
  44.             <set>
  45.                 <value>北京</value>
  46.                 <value>上海</value>
  47.                 <value>广州</value>
  48.             </set>
  49.         </property>
  50.         <property name="score">
  51.             <map>
  52.                 <entry key="JSD1412001" value="78"/>
  53.                 <entry key="JSD1412002" value="68"/>
  54.                 <entry key="JSD1412003" value="94"/>
  55.             </map>
  56.         </property>
  57.         <property name="props">
  58.             <props>
  59.                 <prop key="user">lhh</prop>
  60.                 <prop key="password">123456</prop>
  61.             </props>
  62.         </property>
  63.     </bean>    
  64.     
  65. </beans>

步骤四:写测试代码

创建TestCase测试类,增加测试方法test1,代码如下:


    
    
  1. package com.tarena.test;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import com.tarena.bean.DemoBean;
  6. import com.tarena.bean.MessageBean;
  7. public class TestCase {
  8.     
  9.     /**
  10.      * 注入参数值
  11.      */
  12.     @Test
  13.     public void test1() {
  14.         String cfg = "applicationContext.xml";
  15.         ApplicationContext ctx =
  16.             new ClassPathXmlApplicationContext(cfg);
  17.         MessageBean bean = ctx.getBean("msg", MessageBean.class);
  18.         bean.execute();
  19.     }
  20.     
  21. }

步骤五:执行测试

执行测试方法test1,效果如下图:

图-2

1.4 完整代码

Computer类完整代码如下:

MessageBean类完整代码如下:

applicationContext.xml完整代码如下:

TestCase类完整代码如下:

2 采用引用的方式注入集合

2.1 问题

先声明集合bean,然后采用引用的方式将这些bean注入给MessageBean。

2.2 方案

使用<util>标签声明集合bean,然后在MessageBean下使用<property>标签引用这些集合bean。

2.3 步骤

步骤一:声明bean

在applicationContext.xml中声明集合bean,然后新声明一个MessageBean类型的bean,让这个bean引用集合bean,追加代码如下:


    
    
  1.     <!-- 声明集合bean -->
  2.     <util:list id="langList">
  3.         <value>c++</value>
  4.         <value>python</value>
  5.     </util:list>
  6.     <util:set id="citySet">
  7.         <value>重庆</value>
  8.         <value>天津</value>
  9.     </util:set>
  10.     <util:map id="scoreMap">
  11.         <entry key="JSD1412004" value="90"/>
  12.         <entry key="JSD1412005" value="85"/>
  13.     </util:map>
  14.     <util:properties id="paramProp">
  15.         <prop key="user">tarena</prop>
  16.         <prop key="password">123456</prop>
  17.     </util:properties>
  18.     <!-- 采用引用的方式注入集合 -->
  19.     <bean id="msg2" class="com.tarena.bean.MessageBean">
  20.         <property name="langs" ref="langList"/>
  21.         <property name="cities" ref="citySet"/>
  22.         <property name="score" ref="scoreMap"/>
  23.         <property name="props" ref="paramProp"/>
  24.     </bean>    

步骤二: 写测试代码

在TestCase中增加测试方法test2,追加代码如下:


    
    
  1.     /**
  2.      * 采用引用的方式注入集合
  3.      */
  4.     @Test
  5.     public void test2() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         MessageBean bean = ctx.getBean("msg2", MessageBean.class);
  10.         bean.execute();
  11.     }

步骤三:执行测试

执行test2方法,效果如下图:

图-3

2.4 完整代码

applicationContext.xml完整代码如下:

TestCase类完整代码如下:

3 注入表达式

3.1 问题

通过表达式的方式,给bean注入值。

3.2 方案

新建一个bean,通过表达式的方式引用MessageBean等bean的数据,注入给这个新建的bean。

3.3 步骤

步骤一:创建bean

创建DemoBean,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. public class DemoBean implements Serializable {
  4.     private String name;
  5.     private String lang;
  6.     private String score;
  7.     private int pageSize;
  8.     public void execute() {
  9.         System.out.println("name:" + name);
  10.         System.out.println("lang:" + lang);
  11.         System.out.println("score:" + score);
  12.         System.out.println("pageSize:" + pageSize);
  13.     }
  14.     public String getName() {
  15.         return name;
  16.     }
  17.     public void setName(String name) {
  18.         this.name = name;
  19.     }
  20.     public String getLang() {
  21.         return lang;
  22.     }
  23.     public void setLang(String lang) {
  24.         this.lang = lang;
  25.     }
  26.     public String getScore() {
  27.         return score;
  28.     }
  29.     public void setScore(String score) {
  30.         this.score = score;
  31.     }
  32.     public int getPageSize() {
  33.         return pageSize;
  34.     }
  35.     public void setPageSize(int pageSize) {
  36.         this.pageSize = pageSize;
  37.     }
  38. }

步骤二: 创建资源文件

创建一个资源文件const.properties,用来封装系统常量,代码如下:


    
    
  1. #max rows in one page
  2. PAGE_SIZE=10

步骤三:声明bean

在applicationContext.xml中,通过<util:properties>标签声明一个id=”const”的bean,加载const.properties中的信息。然后再声明DemoBean,使用表达式读取MessageBean和id=”const”的bean,将值注入给DemoBean,追加代码如下:


    
    
  1.     <!-- 声明Properties集合,读取const.properties参数 -->
  2.     <util:properties id="const" location="classpath:const.properties"/>
  3.     <!-- 注入表达式 -->
  4.     <bean id="demo" class="com.tarena.bean.DemoBean">
  5.         <property name="name" value="#{msg.name}"/>
  6.         <property name="lang" value="#{msg.langs[0]}"/>
  7.         <property name="score" value="#{msg.score.JSD1412001}"/>
  8.         <property name="pageSize" value="#{const.PAGE_SIZE}"/>
  9.     </bean>    

步骤四:写测试代码

在TestCase中增加测试方法test3,追加代码如下:


    
    
  1.     /**
  2.      * 注入表达式
  3.      */
  4.     @Test
  5.     public void test3() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         DemoBean bean = ctx.getBean("demo", DemoBean.class);
  10.         bean.execute();
  11.     }

步骤五:执行测试

执行test3方法,效果如下图:

图-4

3.4 完整代码

DemoBean完整代码如下:

const.properties完整代码如下:

applicationContext.xml完整代码如下:

4 使用注解声明bean

4.1 问题

使用Spring注解代替XML配置来声明bean,并使用注解管理bean的作用域和生命周期。

4.2 方案

4.3 步骤

步骤一:创建项目,导入jar包

创建项目Spring02-2,导入Spring开发包,如下图:

图-5

步骤二: 导入配置文件

导入Spring配置文件applicationContext.xml,开启注解扫描,代码如下:


    
    
  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.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
  6.     xmlns:jee="http://www.springframework.org/schema/jee"
  7.     xmlns:tx="http://www.springframework.org/schema/tx"
  8.     xmlns:aop="http://www.springframework.org/schema/aop"
  9.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  10.     xmlns:util="http://www.springframework.org/schema/util"
  11.     xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  12.     xsi:schemaLocation="
  13.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  14.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
  15.         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
  16.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
  17.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  18.         http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
  19.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  20.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  21.         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
  22.     
  23.     <!-- 开启注解扫描 -->
  24.     <context:component-scan base-package="com.tarena"/>
  25.     
  26. </beans>

步骤三:创建并声明bean

创建ExampleBean,并使用@Component注解声明这个bean,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import javax.annotation.PostConstruct;
  4. import javax.annotation.PreDestroy;
  5. import org.springframework.context.annotation.Scope;
  6. import org.springframework.stereotype.Component;
  7. @Component("example")
  8. public class ExampleBean implements Serializable {
  9.     
  10.     public ExampleBean() {
  11.         System.out.println("实例化ExampleBean:" + this);
  12.     }
  13.     
  14.     public void init() {
  15.         System.out.println("初始化ExampleBean");
  16.     }
  17.     
  18.     public void destroy() {
  19.         System.out.println("销毁ExampleBean");
  20.     }
  21.     
  22.     public void execute() {
  23.         System.out.println("执行execute方法");
  24.     }
  25.     
  26. }

步骤四:测试使用注解声明bean

创建测试类TestCase,增加测试方法test1,代码如下:


    
    
  1. package com.tarena.test;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.AbstractApplicationContext;
  5. import org.springframework.context.support.ClassPathXmlApplicationContext;
  6. import com.tarena.bean.DemoBean;
  7. import com.tarena.bean.ExampleBean;
  8. import com.tarena.bean.Manager;
  9. import com.tarena.bean.Programmer;
  10. import com.tarena.bean.Salesman;
  11. import com.tarena.bean.Student;
  12. import com.tarena.bean.Teacher;
  13. public class TestCase {
  14.     
  15.     /**
  16.      * 使用注解声明bean
  17.      */
  18.     @Test
  19.     public void test1() {
  20.         String cfg = "applicationContext.xml";
  21.         ApplicationContext ctx =
  22.             new ClassPathXmlApplicationContext(cfg);
  23.         ExampleBean bean =
  24.             ctx.getBean("example", ExampleBean.class);
  25.         System.out.println(bean);
  26.     }
  27.     
  28. }

执行test1方法,效果如下图:

图-6

步骤五:测试bean的作用域

在TestCase中增加test2方法,追加代码如下:


    
    
  1.     /**
  2.      * 使用注解声明bean的作用域
  3.      */
  4.     @Test
  5.     public void test2() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         ExampleBean bean1 =
  10.             ctx.getBean("example", ExampleBean.class);
  11.         ExampleBean bean2 =
  12.             ctx.getBean("example", ExampleBean.class);
  13.         System.out.println(bean1==bean2);
  14.     }

执行该方法,效果如下图:

图-7

在ExampleBean类上增加@scope(“prototype”),追加代码如下:


    
    
  1. @Component("example")
  2. @Scope("prototype")
  3. public class ExampleBean implements Serializable {

再次执行test2方法,效果如下图:

图-8

步骤六:测试bean的生命周期

在ExampleBean上使用注解声明其初始化方法和销毁方法,并将该bean改为单例的,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import javax.annotation.PostConstruct;
  4. import javax.annotation.PreDestroy;
  5. import org.springframework.context.annotation.Scope;
  6. import org.springframework.stereotype.Component;
  7. @Component("example")
  8. @Scope("singleton")
  9. public class ExampleBean implements Serializable {
  10.     
  11.     public ExampleBean() {
  12.         System.out.println("实例化ExampleBean:" + this);
  13.     }
  14.     
  15.     @PostConstruct
  16.     public void init() {
  17.         System.out.println("初始化ExampleBean");
  18.     }
  19.     
  20.     @PreDestroy
  21.     public void destroy() {
  22.         System.out.println("销毁ExampleBean");
  23.     }
  24.     
  25.     public void execute() {
  26.         System.out.println("执行execute方法");
  27.     }
  28.     
  29. }

在TestCase中增加测试方法test3,追加代码如下:


    
    
  1.     /**
  2.      * 使用注解声明bean的生命周期
  3.      */
  4.     @Test
  5.     public void test3() {
  6.         String cfg = "applicationContext.xml";
  7.         AbstractApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         ExampleBean bean =
  10.             ctx.getBean("example", ExampleBean.class);
  11.         bean.execute();
  12.         ctx.close();
  13.     }

执行该测试方法,效果如下图:

图-9

4.4 完整代码

applicationContext.xml完整代码如下:

ExampleBean完整代码如下:

TestCase完整代码如下:

5 使用@Autowired注解

5.1 问题

使用@Autowired注解注入依赖的bean。

5.2 方案

5.3 步骤

步骤一:创建并声明bean

创建Computer类,并使用@Component注解将其声明到容器中,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class Computer implements Serializable {
  6.     private String mainboard; // 主板
  7.     private String hdd; // 硬盘
  8.     private String ram; // 内存
  9.     public String getMainboard() {
  10.         return mainboard;
  11.     }
  12.     public void setMainboard(String mainboard) {
  13.         this.mainboard = mainboard;
  14.     }
  15.     public String getHdd() {
  16.         return hdd;
  17.     }
  18.     public void setHdd(String hdd) {
  19.         this.hdd = hdd;
  20.     }
  21.     public String getRam() {
  22.         return ram;
  23.     }
  24.     public void setRam(String ram) {
  25.         this.ram = ram;
  26.     }
  27. }

创建Programmer类,并使用@Component注解将其声明到容器中,然后使用@Autowired注解在构造器上将Computer注入进来,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class Programmer implements Serializable {
  8.     private Computer computer;
  9.     @Autowired
  10.     public Programmer(
  11.         @Qualifier("computer") Computer computer) {
  12.         this.computer = computer;
  13.     }
  14.     public Computer getComputer() {
  15.         return computer;
  16.     }
  17.     public void setComputer(Computer computer) {
  18.         this.computer = computer;
  19.     }
  20. }

步骤二: 测试以构造方式注入bean

在TestCase中增加测试方法test4,追加代码如下:


    
    
  1.     /**
  2.      * 使用@Autowired,以构造方式注入bean
  3.      */
  4.     @Test
  5.     public void test4() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         Programmer prog =
  10.             ctx.getBean("programmer", Programmer.class);
  11.         System.out.println(prog);
  12.         System.out.println(prog.getComputer());
  13.     }

执行该测试方法,效果如下图:

图-10

步骤三:创建并声明bean

创建Teacher类,并使用注解将其声明到容器中,然后使用@Autowired注解在set方法上将Computer注入,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class Teacher implements Serializable {
  8.     private Computer computer;
  9.     @Autowired
  10.     public void setComputer(
  11.         @Qualifier("computer") Computer computer) {
  12.         this.computer = computer;
  13.         System.out.println("Teacher");
  14.     }
  15.     
  16.     public Computer getComputer() {
  17.         return computer;
  18.     }
  19. }

步骤四:测试在setter上加注解的方式注入bean

在TestCase里增加测试方法test5,追加代码如下:


    
    
  1.     /**
  2.      * 在setter上使用@Autowired,以setter方式注入bean
  3.      */
  4.     @Test
  5.     public void test5() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         Teacher teacher =
  10.             ctx.getBean("teacher", Teacher.class);
  11.         System.out.println(teacher);
  12.         System.out.println(teacher.getComputer());
  13.     }

执行该测试方法,效果如下图:

图-11

步骤五:创建并声明bean

创建Student类,并使用注解将其声明到容器中,然后在属性上加注解将Computer注入,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class Student implements Serializable {
  8.     @Autowired
  9.     @Qualifier("computer")
  10.     private Computer computer;
  11.     public Computer getComputer() {
  12.         return computer;
  13.     }
  14.     public void setComputer(Computer computer) {
  15.         this.computer = computer;
  16.         System.out.println("Student");
  17.     }
  18. }

步骤六:测试在属性上加注解的方式注入bean

在TestCase中增加测试方法test6,追加代码如下:


    
    
  1.     /**
  2.      * 在属性上使用@Autowired,以setter方式注入bean
  3.      */
  4.     @Test
  5.     public void test6() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         Student student =
  10.             ctx.getBean("student", Student.class);
  11.         System.out.println(student);
  12.         System.out.println(student.getComputer());
  13.     }

执行该测试方法,效果如下图:

图-12

5.4 完整代码

Computer类完整代码如下:

Programmer类完整代码如下:

Teacher类完整代码如下:

Student类完整代码如下:

TestCase类完整代码如下:

6 使用@Resource注解

6.1 问题

使用@Resource注解注入依赖的bean。

6.2 方案

6.3 步骤

步骤一:创建并声明bean

创建Manager类,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import javax.annotation.Resource;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class Manager implements Serializable {
  7.     
  8.     private Computer computer;
  9.     @Resource(name="computer")
  10.     public void setComputer(Computer computer) {
  11.         this.computer = computer;
  12.         System.out.println("Manager");
  13.     }
  14.     public Computer getComputer() {
  15.         return computer;
  16.     }
  17.     
  18. }

步骤二: 测试在setter上加注解的方式注入bean

在TestCase中增加测试方法test7,追加代码如下:


    
    
  1.     /**
  2.      * 在setter上使用@Resource,以setter方式注入bean
  3.      */
  4.     @Test
  5.     public void test7() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         Manager manager =
  10.             ctx.getBean("manager", Manager.class);
  11.         System.out.println(manager);
  12.         System.out.println(manager.getComputer());
  13.     }

执行该测试方法,效果如下图:

图-13

步骤三:创建并声明bean

创建Salesman类,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import javax.annotation.Resource;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class Salesman implements Serializable {
  7.     @Resource
  8.     private Computer computer;
  9.     public Computer getComputer() {
  10.         return computer;
  11.     }
  12.     public void setComputer(Computer computer) {
  13.         this.computer = computer;
  14.         System.out.println("Salesman");
  15.     }
  16. }

步骤四:测试在属性上加注解的方式注入bean

在TestCase中增加测试方法test8,追加代码如下:


    
    
  1.     /**
  2.      * 在属性上使用@Resource,以setter方式注入bean
  3.      */
  4.     @Test
  5.     public void test8() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         Salesman man =
  10.             ctx.getBean("salesman", Salesman.class);
  11.         System.out.println(man);
  12.         System.out.println(man.getComputer());
  13.     }

执行该测试方法,效果如下图:

图-14

6.4 完整代码

Manager类完整代码如下:

Salesman类完整代码如下:

TestCase类完整代码如下:

7 使用注解注入表达式

7.1 问题

使用注解,通过表达式给一个bean注入数据。

7.2 方案

在@Value注解上写表达式,可以给bean注入数据。

7.3 步骤

步骤一:创建资源文件

创建资源文件const.properties,代码如下:


    
    
  1. #max rows in one page
  2. PAGE_SIZE=10

步骤二: 读取资源文件信息

在applicationContext.xml中,使用<util>标签声明一个bean,读取资源文件的信息,追加代码如下:


    
    
  1.     <!-- 声明Properties集合,读取const.properties参数 -->
  2.     <util:properties id="const" location="classpath:const.properties"/>

步骤三:将读取到的信息注入bean

创建DemoBean类,并使用注解将读取的资源文件数据注入到这个bean中,代码如下:


    
    
  1. package com.tarena.bean;
  2. import java.io.Serializable;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class DemoBean implements Serializable {
  7.     private String name;
  8.     private String lang;
  9.     private String score;
  10.     @Value("#{const.PAGE_SIZE}")
  11.     private int pageSize;
  12.     public void execute() {
  13.         System.out.println("name:" + name);
  14.         System.out.println("lang:" + lang);
  15.         System.out.println("score:" + score);
  16.         System.out.println("pageSize:" + pageSize);
  17.     }
  18.     public String getName() {
  19.         return name;
  20.     }
  21.     public void setName(String name) {
  22.         this.name = name;
  23.     }
  24.     public String getLang() {
  25.         return lang;
  26.     }
  27.     public void setLang(String lang) {
  28.         this.lang = lang;
  29.     }
  30.     public String getScore() {
  31.         return score;
  32.     }
  33.     public void setScore(String score) {
  34.         this.score = score;
  35.     }
  36.     public int getPageSize() {
  37.         return pageSize;
  38.     }
  39.     public void setPageSize(int pageSize) {
  40.         this.pageSize = pageSize;
  41.     }
  42. }

步骤四:写测试代码

在TestCase类中增加测试方法test9,追加代码如下:


    
    
  1.     /**
  2.      * 使用注解注入表达式
  3.      */
  4.     @Test
  5.     public void test9() {
  6.         String cfg = "applicationContext.xml";
  7.         ApplicationContext ctx =
  8.             new ClassPathXmlApplicationContext(cfg);
  9.         DemoBean demo =
  10.             ctx.getBean("demoBean", DemoBean.class);
  11.         demo.execute();
  12.     }

步骤五:执行测试

执行test9,效果如下图:

图-15

7.4 完整代码

const.properties完整代码如下:

applicationContext.xml完整代码如下:

DemoBean完整代码如下:

TestCase完整代码如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值