© 版权声明:本文为博主原创文章,转载请注明出处

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的定义及作用域的注解实现的更多相关文章

  1. Spring学习(九)-----Spring bean配置继承

    在 Spring,继承是用为支持bean设置一个 bean 来分享共同的值,属性或配置. 一个子 bean 或继承的bean可以继承其父 bean 的配置,属性和一些属性.另外,子 Bean 允许覆盖 ...

  2. Spring学习(5)---Bean的定义及作用域的注解实现

    Bean管理的注解实现 Classpath扫描与组件管理 类的自动检测与注册Bean <context:annotation-config/> @Component,@Repository ...

  3. Java框架spring 学习笔记(十):bean管理(注解和配置文件混合使用)

    配置文件和注解混合使用 创建对象操作使用配置文件方式实现 注入属性的操作使用注解方式实现 编写BookDao.java和OrderDao.java文件 BookDao.java package com ...

  4. Java框架spring 学习笔记(五):Bean定义继承

    子 bean 的定义继承父定义的配置数据.子定义可以根据需要重写一些值,或者添加其他值. 编写HelloWorld.java package com.example.spring; public cl ...

  5. Java框架spring 学习笔记(三):Bean 的生命周期

    当一个 bean 被实例化时,它可能需要执行一些初始化使它转换成可用状态.当bean不再需要,并且从容器中移除时,需要做一些清除工作.为了定义安装和拆卸一个 bean,我们只要声明init-metho ...

  6. 【Spring学习笔记-3.1】让bean获取spring容器上下文(applicationContext.xml)

    *.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...

  7. Spring Boot实践——用外部配置填充Bean属性的几种方法

    引用:https://blog.csdn.net/qq_17586821/article/details/79802320 spring boot允许我们把配置信息外部化.由此,我们就可以在不同的环境 ...

  8. Spring学习之旅(四)--高级装配Bean

    条件化 bean 有时候我们要满足某种情况才将bean 初始化放入容器中. 基于环境初始化不同的 bean 1.申明接口并创建两个实现类 public interface Teacher { void ...

  9. Spring学习(三)——@PropertySource,@ImportResource,@Bean注解

    @PropertySource注解是将配置文件中 的值赋值给POJO 项目结构如下 一.创建一个Person.Java文件: import org.springframework.boot.conte ...

随机推荐

  1. C 语言实现 php base64_encode

    这是在网上找到的一段代码,因为需求不同,稍微做了下修改,有需要的朋友可以直接复制使用. unsigned char *base64_encode(const unsigned char *str, s ...

  2. 如何修改registry的默认的存储位置

    https://github.com/goharbor/harbor/issues/5375 the adminserver only can show the usage of /data, thi ...

  3. 【03】Vue 之列表渲染及条件渲染

    3.1. 条件渲染 有时候我们要根据数据的情况,决定标签是否进行显示或者有其他动作.最常见的就是,表格渲染的时候,如果表格没有数据,就显示无数据.如果有数据就显示表格数据. Vue帮我们提供了一个v- ...

  4. Maven构建多模块项目

    使用Maven构建多模块项目 转自:http://www.cnblogs.com/xdp-gacl/p/4242221.html 在平时的Javaweb项目 开发中为了便于后期的维护,我们一般会进行分 ...

  5. poj 2441 Arrange the Bulls

    Arrange the Bulls Time Limit: 4000MS   Memory Limit: 65536K Total Submissions: 5427   Accepted: 2069 ...

  6. [Codeforces Round #351 Div. 2] 673A Bear and Game

    A. Bear and Game time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  7. Dictionary To Dynamic

    原文发布时间为:2012-12-25 -- 来源于本人的百度文章 [由搬家工具导入] public static class DictionaryExt    {        /// <sum ...

  8. layui 自定义表单验证 以及提交表单

    订购数量</span> <span style="color: red">*</span>: <input type="text ...

  9. Python Challenge 第九关

    第九关只有一幅图,上面有一些黑点.网页名字叫:connect the dots.可能是要把这些点连起来. 查看源代码,果然有两个整数集合 first 和 second.并且有个提示:first+sec ...

  10. activity dialog生命周期

    Android生命周期包括以下几个状态: onCreate(Bundle savedInstanceState):可以进行一些初始化的工作在activity第一次被创建的时候调用.这里是你做所有初始化 ...