Spring学习九----------Bean的配置之Bean的定义及作用域的注解实现
© 版权声明:本文为博主原创文章,转载请注明出处
Spring Bean常用注解
@Component:通常注解,可用于任何Bean
@Repository:通常用于注解DAO层,即持久层
@Service:通常用于注解Service层,即服务层
@Controller:通常用于注解Controller层,即控制层
类的自动检测及Bean的注册
<context:component-scan base-package=""/>:自动扫描base-package定义的包或其子包下的类,并将带有@Component,@Controller,@Service,@Repository等注解的类自动注册到IOC容器中。
<context:annotation-config/>:隐式的向Spring容器中注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 和RequiredAnnotationBeanPostProcessor 这四个BeanPostProcessor。
<context:component-scan/>包含了<context:annotation-config/>,因此使用<context:component-scan/>就不用再使用<context:annotation-config/>
定义Bean
Bean名称由BeanNameGenerator生成(@Component,@Controller,@Service,@Repository都有个name属性用于显示的指定Bean Name;默认是类名首字母小写)
也可使用<context:component-scan/>中的name-generator自定义Bean的命名策略,但是要实现BeanNameGenerator接口并且包含一个无参构造器
作用域
@Scope注解标识Bean的作用域。默认是singleton。
实例
1.项目结构

2.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.spring</groupId>
<artifactId>Spring-BeanAnnotation</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-BeanAnnotation Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<spring.version>4.3.7.RELEASE</spring.version>
</properties> <dependencies>
<!-- junit依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies> <build>
<finalName>Spring-BeanAnnotation</finalName>
</build> </project>
3.spring-beanannotation.xml
<?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"> <!-- 自动扫描包下的Bean并注册到IOC容器中 -->
<context:component-scan base-package="org.spring.annotation.bean"/> </beans>
4.BeanAnnotation.java
package org.spring.annotation.bean; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; @Scope("prototype")
@Component
public class BeanAnnotation { public void say() { System.out.println("注解方式获取成功"); } public void hasCode() { System.out.println("BeanAnnotation:" + this.hashCode()); } }
5.TestBase.java
package org.spring.annotation.test; import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils; public class TestBase { private ClassPathXmlApplicationContext context;
private String xmlPath; /**
* 无参构造器
*/
public TestBase() { } /**
* 含参构造器,初始化配置文件路径
*
* @param xmlPath
* 配置文件路径
*/
public TestBase(String xmlPath) { this.xmlPath = xmlPath; } /**
* 初始化spring的IOC容器
*/
@Before
public void before() { if(StringUtils.isEmpty(xmlPath)) {//配置文件默认路径
xmlPath = "classpath:spring-*.xml";
}
//加载配置文件到spring容器中
context = new ClassPathXmlApplicationContext(xmlPath.split("[,\\s]+"));
//启动IOC容器s
context.start(); } /**
* 销毁容器
*/
@After
public void after() { if(context != null){
context.destroy();
} } /**
* 根据bean id获取bean对象
*/
public Object getBean(String id) { return context.getBean(id); } }
6.TestBeanAnnotation.java
package org.spring.annotation.test; import org.junit.Test;
import org.spring.annotation.bean.BeanAnnotation; public class TestBeanAnnotation extends TestBase { /**
* 构造器传入spring配置文件路径
*/
public TestBeanAnnotation() { super("classpath:spring-beanannotation.xml"); } /**
* 测试注解方式获取bean对象
*/
@Test
public void testBeanAnnotation() { BeanAnnotation bean = (BeanAnnotation) super.getBean("beanAnnotation");
bean.say(); } /**
* 测试注解方式的Bean的作用域
*/
@Test
public void testBeanScope() { BeanAnnotation bean = (BeanAnnotation) super.getBean("beanAnnotation");
bean.hasCode(); BeanAnnotation bean2 = (BeanAnnotation) super.getBean("beanAnnotation");
bean2.hasCode(); } }
7.效果预览

参考:http://www.imooc.com/video/4030
Spring学习九----------Bean的配置之Bean的定义及作用域的注解实现的更多相关文章
- Spring学习(九)-----Spring bean配置继承
在 Spring,继承是用为支持bean设置一个 bean 来分享共同的值,属性或配置. 一个子 bean 或继承的bean可以继承其父 bean 的配置,属性和一些属性.另外,子 Bean 允许覆盖 ...
- Spring学习(5)---Bean的定义及作用域的注解实现
Bean管理的注解实现 Classpath扫描与组件管理 类的自动检测与注册Bean <context:annotation-config/> @Component,@Repository ...
- Java框架spring 学习笔记(十):bean管理(注解和配置文件混合使用)
配置文件和注解混合使用 创建对象操作使用配置文件方式实现 注入属性的操作使用注解方式实现 编写BookDao.java和OrderDao.java文件 BookDao.java package com ...
- Java框架spring 学习笔记(五):Bean定义继承
子 bean 的定义继承父定义的配置数据.子定义可以根据需要重写一些值,或者添加其他值. 编写HelloWorld.java package com.example.spring; public cl ...
- Java框架spring 学习笔记(三):Bean 的生命周期
当一个 bean 被实例化时,它可能需要执行一些初始化使它转换成可用状态.当bean不再需要,并且从容器中移除时,需要做一些清除工作.为了定义安装和拆卸一个 bean,我们只要声明init-metho ...
- 【Spring学习笔记-3.1】让bean获取spring容器上下文(applicationContext.xml)
*.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...
- Spring Boot实践——用外部配置填充Bean属性的几种方法
引用:https://blog.csdn.net/qq_17586821/article/details/79802320 spring boot允许我们把配置信息外部化.由此,我们就可以在不同的环境 ...
- Spring学习之旅(四)--高级装配Bean
条件化 bean 有时候我们要满足某种情况才将bean 初始化放入容器中. 基于环境初始化不同的 bean 1.申明接口并创建两个实现类 public interface Teacher { void ...
- Spring学习(三)——@PropertySource,@ImportResource,@Bean注解
@PropertySource注解是将配置文件中 的值赋值给POJO 项目结构如下 一.创建一个Person.Java文件: import org.springframework.boot.conte ...
随机推荐
- vue2搭建简易spa
使用vue-cli来配置webpack,webpack是一个打包工具,使程序模块化 全局安装vue-cli: npm install -g vue-cli 安装好后,使用vue-cli脚手架配置web ...
- poj 1743 Musical Theme 后缀自动机/后缀数组/后缀树
题目大意 直接用了hzwer的题意 题意:有N(1 <= N <=20000)个音符的序列来表示一首乐曲,每个音符都是1..88范围内的整数,现在要找一个重复的主题."主题&qu ...
- pat 团体天梯赛 L1-039. 古风排版
L1-039. 古风排版 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 中国的古人写文字,是从右向左竖向排版的.本题就请你编写 ...
- mysql-count与sum
参考:https://www.jb51.net/article/141238.htm 建立时间临时辅助表:https://blog.csdn.net/qq_36226453/article/detai ...
- 理解printk函数【转】
转自:http://blog.csdn.net/Tommy_wxie/article/details/17026391 理解printk函数 Printk函数是在开发驱动过程中经常用到的一个函数,作用 ...
- LeetCode OJ-- LRU Cache ***@
https://oj.leetcode.com/problems/lru-cache/ 涨姿势的一道题,相当于实现一种数据结构,实现最近最少使用数据结构. // 用来记录 前后节点都是什么 类似链表上 ...
- Educational Codeforces Round 34 B. The Modcrab【模拟/STL】
B. The Modcrab time limit per test 1 second memory limit per test 256 megabytes input standard input ...
- Linux内核Crash分析
转载自:http://linux.cn/article-3475-1.html 在工作中经常会遇到一些内核crash的情况,本文就是根据内核出现crash后的打印信息,对其进行了分析,使用的内核版本为 ...
- ios获得文件字节总数
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.finalPath err ...
- flask的安全注意事项,如何防范XSS、CSRF、JSON安全
参考官方文档:http://docs.jinkan.org/docs/flask/security.html 1.xss Flask 配置 Jinja2 自动转义所有值,除非显式地指明不转义.这就排除 ...