Spring4笔记5--基于注解的DI(依赖注入)
基于注解的DI(依赖注入):
对于 DI 使用注解,将不再需要在 Spring 配置文件中声明 Bean 实例。只需要在 Spring 配置文件中配置组件扫描器,用于在指定的基本包中扫描注解。
<?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">
<!-- 只扫描子包,不扫描当前包 -->
<!-- <context:component-scan base-package="com.tongji.*"/> -->
<!-- 先扫描子包,再扫描当前包 -->
<!-- <context:component-scan base-package="com.tongji"/> --> <context:component-scan base-package="com.tongji.di01"/>
</beans>
注意:添加的约束http://www.springframework.org/schema/context/spring-context.xsd
注解基本注入:
package com.tongji.di01; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //与本注解具有相同功能的注解还有三个:
//@Repository:注解在Dao接口的实现类上,表示当前Dao类为组件
//@Service:注解在Service接口的实现类上,表示当前Service类为组件
//@Controller:注解在Controller接口的实现类上,表示当前Controller类为组件(SpringMVC)
@Component("student") //表明当前类为组件,容器创建的这个组件对象名称为myStudent,相当于<bean/>的id属性
@Scope("prototype") //设置Bean的作用范围,默认是singleton
public class Student {
@Value("张三") //为name属性赋值
private String name;
private int age; public String getName() {
return name;
} public void setName(String name) {
System.out.println("执行setName");
this.name = name;
} public int getAge() {
return age;
} @Value("23") //可以将该注解放到set上
public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
} }
解释:注解注入时,POJO类可以没有setXXX()方法,但还是写上去比较好。
注解域属性的自动注入:
(1) 用Spring自带的注解实现:
@Component("myStudent")
@Scope("prototype")
public class Student {
@Value("张三")
private String name;
@Value("23")
private int age;
@Autowired //byType方式自动注入
private School school;
@Component("myStudent")
@Scope("prototype")
public class Student {
@Value("张三")
private String name;
@Value("23")
private int age;
@Autowired
@Qualifier("mySchool") //byName方式自动注入
private School school;
补充:@Autowired 还有一个属性 required,默认值为 true,表示当匹配失败后,会终止程序运行。若将其值设置为 false,则匹配失败,将被忽略,未匹配的属性值为 null。
(2)使用JDK提供的注解实现:
@Component("myStudent")
@Scope("prototype")
public class Student {
@Value("张三")
private String name;
@Value("23")
private int age;
@Resource //byType方式自动注入
private School school;
@Component("myStudent")
@Scope("prototype")
public class Student {
@Value("张三")
private String name;
@Value("23")
private int age;
@Resource(name="mySchool") //byName方式自动注入
private School school;
注解Bean的定制声明始末:
@PostConstruct
public void postInit() {
System.out.println("初始化完毕之后");
} @PreDestroy
public void preDestory() {
System.out.println("销毁之前");
}
在方法上使用@PostConstruct,与原来的 init-method 等效。在方法上使用@PreDestroy,与 destroy-method 等效。
使用JavaConfig进行配置:
JavaConfig,是在 Spring 3.0 开始从一个独立的项目并入到 Spring 中的。JavaConfig 可以看成一个用于完成 Bean 装配的配置文件,只不过是程序员使用 Java 自己编写的。
package com.tongji.di07; import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration //表明当前POJO类将会被当作配置文件来使用,即Spring容器
public class MyJavaConfig { @Bean(name="mySchool") //表明当前方法的返回值为一个Bean对象
public School mySchoolCreater() {
return new School("清华大学");
} @Bean(name="school") //byName方式需要定义的该Bean的name值与被注入的属性名相同
public School mySchoolCreater2() {
return new School("北京大学");
} //@Bean(name="myStudent", autowire=Autowire.BY_TYPE) //byType方式自动注入
@Bean(name="myStudent", autowire=Autowire.BY_NAME) //byName方式自动注入
public Student myStudentCreater() {
return new Student("赵六",26);
}
}
解释:此时School类和Student类就不需要注解了。
使用 junit4 测试 Spring:
对 Spring 程序的运行,首先需要创建容器对象,而后还要从容器中获取对象,再对其进行执行。但,JUnit4 对 Spring 程序有专门的测试方法。
package com.tongji.di08; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //使用Spring的测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:com/tongji/di08/applicationContext.xml")
public class MyTest2 extends AbstractJUnit4SpringContextTests { @Autowired //byType
@Qualifier("myStudent") //byName
private Student student;
@Test
public void test01() {
System.out.println(student);
} }
注意:Student对象的注入方式可以是基于XML的,也可以是基于注解的。
注解与XML共同使用:
注解的好处是,配置方便,直观。但其弊端也显而易见:以硬编码的方式写入到了 Java代码中,其修改是需要重新编译代码的。
XML 配置方式的最大好处是,对其所做修改,无需编译代码,只需重启服务器即可将新的配置加载。
若注解与 XML 同用,XML 的优先级要高于注解。这样做的好处是,需要对某个 Bean做修改,只需修改配置文件即可。当然,此时,Bean 类要有 setXXX() 或构造器。
Spring4笔记5--基于注解的DI(依赖注入)的更多相关文章
- 开涛spring3(12.2) - 零配置 之 12.2 注解实现Bean依赖注入
12.2 注解实现Bean依赖注入 12.2.1 概述 注解实现Bean配置主要用来进行如依赖注入.生命周期回调方法定义等,不能消除XML文件中的Bean元数据定义,且基于XML配置中的依赖注入的 ...
- 注解实现Bean依赖注入
12.2.1 概述 注解实现Bean配置主要用来进行如依赖注入.生命周期回调方法定义等,不能消除XML文件中的Bean元数据定义,且基于XML配置中的依赖注入的数据将覆盖基于注解配置中的依赖注入的数 ...
- SSM-Spring-07:Spring基于注解的di注入
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 注解: 说起注解,哇哦,每个人都或多或少的用到过 像什么@Overried,@Test,@Param等等之前就 ...
- 三大框架 之 Spring(IOC控制反转、DI依赖注入)
目录 常用词汇 left join与left outer join的区别 Struts2的标签库导入 Spring Spring概述 什么是Spring spring特点 下载 IOC 什么IOC 传 ...
- 谈谈php里的IOC控制反转,DI依赖注入
理论 发现问题 在深入细节之前,需要确保我们理解"IOC控制反转"和"DI依赖注入"是什么,能够解决什么问题,这些在维基百科中有非常清晰的说明. 控制反转(In ...
- Spring:(二)DI依赖注入方式
DI 依赖注入 DI(Dependency Injection)依赖注入,说简单一点就将类里面的属性在创建类的过程中给属性赋值,即将对象依赖属性(简单值,集合,对象)通过配置设值给该对象. 属性注入的 ...
- 一) Spring 介绍、IOC控制反转思想与DI依赖注入
一.spring介绍1.IOC反转控制思想(Inversion of Control)与DI依赖注入(Dependency Injection)2.AOP面向切面的编程思想与动态代理3.作用:项目的粘 ...
- Spring-初识Spring框架-IOC控制反转(DI依赖注入)
---恢复内容开始--- IOC :控制反转 (DI:依赖注入)使用ioc模式开发 实体类必须有无参构造方法1.搭建Spring环境下载jarhttp://maven.springframework. ...
- 轻松学,浅析依赖倒置(DIP)、控制反转(IOC)和依赖注入(DI) 依赖注入和控制反转的理解,写的太好了。
轻松学,浅析依赖倒置(DIP).控制反转(IOC)和依赖注入(DI) 2017年07月13日 22:04:39 frank909 阅读数:14269更多 所属专栏: Java 反射基础知识与实战 ...
随机推荐
- 第211天:git和github的区别和使用详解
一.git 1.什么是git 它是一个源代码管理工具,在一个项目中,凡是由开发人员编写的都算是源代码,源代码有必要管理起来,让源代码可以被追溯,主要记录每次变更了什么,谁主导这次变化.人为的维护比较麻 ...
- YARN结构分析与工作流程
YARN Architecture Link: http://hadoop.apache.org/docs/r2.7.2/hadoop-yarn/hadoop-yarn-site/YARN.html ...
- PHP Warning: strftime(): It is not safe to rely on the system's timezone set
当运行一些程序时,在httpd日志中会有如下警告日志: PHP Warning: strftime(): It is not safe to rely on the system's timezon ...
- BZOJ 3295 动态逆序对 | CDQ分治
BZOJ 3295 动态逆序对 这道题和三维偏序很类似.某个元素加入后产生的贡献 = time更小.pos更小.val更大的元素个数 + time更小.pos更大.val更小的元素个数. 分别用类似C ...
- UOJ #126 【NOI2013】 快餐店
题目链接:快餐店 震惊!某ZZ选手此题调了一天竟是因为……>>点击查看 一般碰到这种基环树的题都要先想想树上怎么做.这道题如果是在树上的话……好像求一遍直径就做完了?答案就是直径长度的一半 ...
- mybatis.5.动态SQL
1.动态SQL,解决关联sql字符串的问题,mybatis的动态sql基于OGNL表达式 if语句,在DeptMapper.xml增加如下语句; <select id="selectB ...
- Solr7.2的安装与使用
单机安装Solr服务: https://www.cnblogs.com/LUA123/p/7906774.html extend: install_solr_service.sh 参数说明: 安装脚本 ...
- OCR论文整理
论文地址:https://github.com/ChanChiChoi/awesome-ocr 下面是已经看过的论文: CTPN CRNN TextBoxes EAST FOTS PixelLink
- 5.Qt模块简介
Qt 5 与 Qt 4 最大的一个区别之一是底层架构有了修改.Qt 5 引入了模块化的概念,将众多功能细分到几个模块之中.Qt 4 也有模块的概念,但是是一种很粗的划分,而 Qt 5 则更加细化.本节 ...
- 【题解】【雅礼集训 2017 Day5】远行 LOJ 6038 LCT
Prelude 快要THUWC了,练一练板子. 传送到LOJ:o(TヘTo) Solution 首先有一条定理. 到树中任意一点的最远点一定是直径的两个端点之一. 我也不会证反正大家都在用,似乎可以用 ...