Spring框架第四篇之基于注解的DI注入
一、说明
与@Component注解功能相同,但意义不同的注解还有三个:
1)@Repository:注解在Dao实现类上
2)@Service:注解在Service实现类上
3)@Controller:注解在SpringMVC的处理器上
Bean作用域:
@Scope("prototype"):用于指定对象创建模式,可以是单例模式或者原型模式,默认是singleton
基本类型属性注入:
@Value
@Autowired:byType方式的注解式注入,即根据类型注解
@Qualifier("mySchool"):byName方式的注解式注入,在使用@Qualifier时必须与@Autowired联合使用
域属性注解:
@Resource:不加name属性则为byType方式的注解式注入,但前提是注入的对象只能有一个
@Resource(name="mySchool"):byName方式的注解式注入
Bean的生命始末:
@PostConstruct:当前Bean初始化刚完毕
@PreDestroy:当前Bean即将被销毁
@Configuration:表示当前类充当Spring容器,即所有的Bean将由这个类来创建
注意:
在举例之前声明几个问题:
1、注解需要依赖spring-aop-4.3.9.RELEASE.jar包,所以需要导入依赖包。

2、使用注解方式注入,配置文件需要添加约束头文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">
也可以自己从Spring的说明文档中找到此头文件:

3、如果使用到了SpringJUnit4测试,则还需要导入spring-test-4.3.9.RELEASE.jar包
二、举例
1、首先创建一个School类:
package com.ietree.spring.basic.annotation.demo1; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component("mySchool")
public class School { @Value(value = "清华大学")
private String name; public School() {
super();
} public School(String name) {
super();
this.name = name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "School [name=" + name + "]";
} }
创建Student类:
package com.ietree.spring.basic.annotation.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.stereotype.Component; /**
* 说明:
* 与@Component注解功能相同,但意义不同的注解还有三个:
* 1)@Repository:注解在Dao实现类上
* 2)@Service:注解在Service实现类上
* 3)@Controller:注解在SpringMVC的处理器上
*
* Bean作用域:
* @Scope("prototype"):用于指定对象创建模式,可以是单例模式或者原型模式,默认是singleton
*
* 基本类型属性注入:
* @Value
*
* @Autowired:byType方式的注解式注入,即根据类型注解
* @Qualifier("mySchool"):byName方式的注解式注入,在使用@Qualifier时必须与@Autowired联合使用
*
* 域属性注解:
* @Resource:不加name属性则为byType方式的注解式注入,但前提是注入的对象只能有一个
* @Resource(name="mySchool"):byName方式的注解式注入
*
* Bean的生命始末:
* @PostConstruct:当前Bean初始化刚完毕
* @PreDestroy:当前Bean即将被销毁
*/
//@Scope("prototype")
@Component("myStudent")
public class Student { @Value(value = "小明")
private String name; @Value(value = "25")
private int age; // @Autowired
// @Qualifier("mySchool")
// @Resource(name="mySchool")
@Resource
private School school;// 对象属性,也叫做域属性 public Student() {
super();
} public Student(String name, int age) {
super();
this.name = name;
this.age = age;
} public void setName(String name) {
System.out.println("执行setName()");
this.name = name;
} public void setAge(int age) {
System.out.println("执行setAge()");
this.age = age;
} public void setSchool(School school) {
this.school = school;
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", school=" + school + "]";
} @PostConstruct
public void initAfter(){
System.out.println("当前Bean初始化刚完毕");
} @PreDestroy
public void preDestroy(){
System.out.println("当前Bean即将被销毁");
}
}
创建MyJavaConfig类:
package com.ietree.spring.basic.annotation.demo1; import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; /**
* @Configuration:表示当前类充当Spring容器,即所有的Bean将由这个类来创建
*/
@Configuration
public class MyJavaConfig { @Bean(name="mySchool")
public School mySchoolCreator(){
return new School("清华大学");
} // autowire=Autowire.BY_TYPE:指从当前类这个容器中查找与域属性的类型具有is-a关系的Bean
// autowire=Autowire.BY_NAME:指从当前类这个容器中查找与域属性同名的Bean
@Bean(name="myStudent", autowire=Autowire.BY_TYPE)
public Student myStudentCreator(){
return new Student("小明", 25);
}
}
创建配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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"> <!-- 扫描 com.ietree.spring.basic.annotation.demo1这个包及其子包 -->
<context:component-scan base-package="com.ietree.spring.basic.annotation.demo1"/> <!-- 扫描 com.ietree.spring.basic这个包的子包 -->
<context:component-scan base-package="com.ietree.spring.basic.*"/> </beans>
创建测试类:
package com.ietree.spring.basic.annotation.demo1; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:com/ietree/spring/basic/annotation/demo1/applicationContext.xml")
public class MyTest { @Autowired
private Student student; @Test
public void test01() { String resource = "com/ietree/spring/basic/annotation/demo1/applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(resource); School school = (School) ctx.getBean("mySchool");
System.out.println(school); Student student = (Student) ctx.getBean("myStudent");
System.out.println(student); ((ClassPathXmlApplicationContext)ctx).close();
} public void test02(){
System.out.println(student);
} }
注意:如果配置了XML,同时又配置了注解,那么程序会首先选择XML配置创建对象。
Spring框架第四篇之基于注解的DI注入的更多相关文章
- Spring框架第三篇之基于XML的DI注入
一.注入分类 Bean实例在调用无参构造器创建空值对象后,就要对Bean对象的属性进行初始化.初始化是由容器自动完成的,称为注入.根据注入方式的不同,常用的有两类:设值注入.构造注入.实现特定接口注入 ...
- SSM-Spring-07:Spring基于注解的di注入
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 注解: 说起注解,哇哦,每个人都或多或少的用到过 像什么@Overried,@Test,@Param等等之前就 ...
- 07 Spring框架 依赖注入(四)基于注解的依赖注入
前面几节我们都在使用xml进行依赖的注入,但是在实际的开发中我们往往偏爱于使用注解进行依赖注入,因为这样更符合我们人的思维,并且更加快捷,本节就来讲述Spring基于注解的依赖注入: 信息注入注解 @ ...
- Spring的第四天AOP之注解版
Spring的第四天AOP之注解版 ssm框架 spring 在上一篇博客中,介绍了Spring的AOP的xml版本的使用,在这篇博客中,我将介绍一下,注解版的使用. 常用注解 注解 通知 @Aft ...
- Spring声明式事务管理(基于注解方式实现)
----------------------siwuxie095 Spring 声明式事务管理(基于注解方式实现) 以转 ...
- 解决Spring框架的Dao层改用@Repository注解,无法使用JdbcDaoSupport的问题
解决Spring框架的Dao层改用@Repository注解,无法使用JdbcDaoSupport的问题 Alternatively, create an own implementation of ...
- 使用Spring框架入门四:基于注解的方式的AOP的使用
一.简述 前面讲了基于XML配置的方式实现AOP,本文简单讲讲基于注解的方式实现. 基于注解的方式实现前,要先在xml配置中通过配置aop:aspectj-autoproxy来启用注解方式注入. &l ...
- spring框架学习(四)——注解方式AOP
注解配置业务类 使用@Component("s") 注解ProductService 类 package com.how2java.service; import org.spri ...
- Spring Cloud第四篇 | 客户端负载均衡Ribbon
本文是Spring Cloud专栏的第四篇文章,了解前三篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Cl ...
随机推荐
- Ci 错误 In order to use the Session class you are required to set an encryption key in your config file.
说明自己没有给session 加密 ,在配置文件config中 $config['encryption_key'] = '2rf3f3fwefwefwef2';
- IoC最大的好处是什么
IoC最大的好处是什么?因为把对象生成放在了XML里定义,所以当我们需要换一个实现子类将会变成很简单(一般这样的对象都是实现于某种接口的),只要修改XML就可以了,这样我们甚至可以实现对象的热插拨(有 ...
- strust2自定义interceptor的基本方法及操作
需求:制作一个网站需要用户登陆后才能查看,即一个权限的问题 1.首先明确在用户没登陆前有两个Action请求是可以通过的,即注册和登陆. 2.创建拦截器,如UserLoginInterceptor.j ...
- bootstrap基础学习五篇
bootstrap表格 Bootstrap 提供了一个清晰的创建表格的布局.下表列出了 Bootstrap 支持的一些表格元素: 标签 描述 <table> 为表格添加基础样式. < ...
- loadruner11 socket脚本-10053错误
背景: socket 10053异常:软件主动放弃一个连接,原因是超时或协议错误.如果LR客户端报10053异常,说明LR在执行套接字操作时,发生通信超时.网络中断或其它异常,主动将Socket连接断 ...
- 去除 \ufeff
语言:python 编程工具:pycharm 硬件环境:win10 64位 读取文件过程中发现一个问题:已有记事本文件(非空),转码 UTF-8,复制到pycharm中,在开始位置打印结果会出现 \ ...
- Docker 如何把镜像上传到docker hub
1 首先你得准备一个hub 的帐号, 去 https://hub.docker.com 注册吧! 2 在hub那里新建一个仓库, 这个就类似于github那边的..create ---> cre ...
- MySQL------如何卸载与安装
1.安装 转载:http://wenda.so.com/q/1471475177723102?src=140 2.卸载 转载:http://jingyan.baidu.com/article/3d69 ...
- com.mysql.jdbc.MysqlDataTruncation: Data trunca...
连接的是mysql数据库,插入数据时,控制台报: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for colu ...
- 【BZOJ4297】[PA2015]Rozstaw szyn 树形DP
[BZOJ4297][PA2015]Rozstaw szyn Description 给定一棵有n个点,m个叶子节点的树,其中m个叶子节点分别为1到m号点,每个叶子节点有一个权值r[i].你需要给剩下 ...