基于注解的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(依赖注入)的更多相关文章

  1. 开涛spring3(12.2) - 零配置 之 12.2 注解实现Bean依赖注入

    12.2  注解实现Bean依赖注入 12.2.1  概述 注解实现Bean配置主要用来进行如依赖注入.生命周期回调方法定义等,不能消除XML文件中的Bean元数据定义,且基于XML配置中的依赖注入的 ...

  2. 注解实现Bean依赖注入

    12.2.1  概述 注解实现Bean配置主要用来进行如依赖注入.生命周期回调方法定义等,不能消除XML文件中的Bean元数据定义,且基于XML配置中的依赖注入的数据将覆盖基于注解配置中的依赖注入的数 ...

  3. SSM-Spring-07:Spring基于注解的di注入

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 注解: 说起注解,哇哦,每个人都或多或少的用到过 像什么@Overried,@Test,@Param等等之前就 ...

  4. 三大框架 之 Spring(IOC控制反转、DI依赖注入)

    目录 常用词汇 left join与left outer join的区别 Struts2的标签库导入 Spring Spring概述 什么是Spring spring特点 下载 IOC 什么IOC 传 ...

  5. 谈谈php里的IOC控制反转,DI依赖注入

    理论 发现问题 在深入细节之前,需要确保我们理解"IOC控制反转"和"DI依赖注入"是什么,能够解决什么问题,这些在维基百科中有非常清晰的说明. 控制反转(In ...

  6. Spring:(二)DI依赖注入方式

    DI 依赖注入 DI(Dependency Injection)依赖注入,说简单一点就将类里面的属性在创建类的过程中给属性赋值,即将对象依赖属性(简单值,集合,对象)通过配置设值给该对象. 属性注入的 ...

  7. 一) Spring 介绍、IOC控制反转思想与DI依赖注入

    一.spring介绍1.IOC反转控制思想(Inversion of Control)与DI依赖注入(Dependency Injection)2.AOP面向切面的编程思想与动态代理3.作用:项目的粘 ...

  8. Spring-初识Spring框架-IOC控制反转(DI依赖注入)

    ---恢复内容开始--- IOC :控制反转 (DI:依赖注入)使用ioc模式开发 实体类必须有无参构造方法1.搭建Spring环境下载jarhttp://maven.springframework. ...

  9. 轻松学,浅析依赖倒置(DIP)、控制反转(IOC)和依赖注入(DI) 依赖注入和控制反转的理解,写的太好了。

    轻松学,浅析依赖倒置(DIP).控制反转(IOC)和依赖注入(DI) 2017年07月13日 22:04:39 frank909 阅读数:14269更多 所属专栏: Java 反射基础知识与实战   ...

随机推荐

  1. Qt 删除目录

    删除目标的目录,若该目录下有子目录,一并删除. //判断是否存在子目录 bool judgeDir(QDir dir) { dir.setFilter(QDir::AllEntries | QDir: ...

  2. C++ STL 常用拷贝和替换算法

    C++ STL 常用拷贝和替换算法 copy() 复制 vector<int> vecIntA; vecIntA.push_back(1); vecIntA.push_back(3); v ...

  3. c++11 继承构造

    c++11 继承构造 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #includ ...

  4. Java开发23种设计模式

    设计模式(Design Patterns) -- --  -- 可复用面向对象软件的基础 设计模式(Design Patterns)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. ...

  5. 【BZOJ2024】舞会(动态规划,容斥,高精度)

    [BZOJ2024]舞会(动态规划,容斥,高精度) 题面 BZOJ 洛谷 题解 这种关系显然要先排序才不会不想影响. 设\(f[i][j]\)表示前\(i\)个女生中,选了\(j\)个女生配对,并且女 ...

  6. 【BZOJ4140】共点圆加强版(二进制分组)

    [BZOJ4140]共点圆加强版(二进制分组) 题面 BZOJ 题解 我卡精度卡了一天.... 之前不强制在线的做法是\(CDQ\)分治,维护一个凸壳就好了. 现在改成二进制分组,每次重建凸壳就好了. ...

  7. Merge Two Sorted Lists - LeetCode

    目录 题目链接 注意点 解法 小结 题目链接 Merge Two Sorted Lists - LeetCode 注意点 两个链表长度可能不一致 解法 解法一:先比较两个链表长度一致的部分,多余的部分 ...

  8. 如何将现有 git 仓库中的子项目单独抽出来作为一个独立仓库并保留其提交历史

    很多时候,我们会遇到在一个git仓库下包含了很多小项目,但是随着有些项目的需求逐渐增大或则市场需求,我们需要将其抽离出来,作为一个单独的项目进行维护并开发. 但是,如果直接拷贝文件粘贴到新建的git ...

  9. BP神经网络人口预测程序(matlab实现)

    自己测试人口预测的matlab实现: x=[54167    55196    56300    57482    58796    60266    61465    62828    64653  ...

  10. unity还原three之旋转

    http://www.360doc.com/content/16/0829/14/12282510_586760119.shtml unity使用左手坐标系,另外在做旋转的时候必须弄清楚旋转坐标轴和旋 ...