Spring入门篇 学习笔记

@Bean

@Bean 标识一个用于配置和初始化一个由 Spring IoC 容器管理的新对象的方法,类似于 XML 配置文件的

可以在 Spring 的 @Configuration 注解的类中使用 @Bean 注解任何方法,在方法里面创建对象返回

@Configuration
public class AppConfig{
@Bean
public MyService myService(){
return new MyServiceImpl();
}
}

示例

新建类:

public interface Store<T> {

}

public class StringStore implements Store<String> {

	public void init() {
System.out.println("This is init.");
} public void destroy() {
System.out.println("This is destroy.");
} } @Configuration
public class StoreConfig { @Bean(initMethod = "init", destroyMethod = "destroy")// 如果没有指定 name,那么name 为方法的名称
public StringStore stringStore() {
return new StringStore();
} }

添加测试:

@RunWith(BlockJUnit4ClassRunner.class)
public class TestJavabased extends UnitTestBase { public TestJavabased() {
super("classpath*:spring-beanannotation.xml");
} @Test
public void test() {
Store store = super.getBean("stringStore");
System.out.println(store.getClass().getName());
} }

@Bean 默认是单例的,如果要改变作用域范围,可以再添加 @Scope 注解

@ImportResource

<beans>

    <context:annotation-config/>
<!--加载资源文件-->
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/> <bean class="com.acme.AppConfig"/> <!--引用资源文件中的配置内容-->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.username}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean> </beans>

使用 @ImportResource 可以代替上面 XML 配置:

@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig{
@Value("${jdbc.url")
private String url; @Value("${jdbc.username}")
private String username; @Value("${jdbc.password}")
private String password; @Bean
public DataSource dataSource(){
return new DriverManagerDataSource(url, username, password);
}
}

示例:

添加类:

public class MyDriverManager {

	public MyDriverManager(String url, String userName, String password) {
System.out.println("url : " + url);
System.out.println("userName: " + userName);
System.out.println("password: " + password);
} }

添加配置文件 config.properties:

jdbc.username=root
jdbc.password=root
jdbc.url=127.0.0.1

添加配置文件 config.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" > <context:property-placeholder location="classpath:/config.properties"/> </beans>

修改类 StoreConfig:

@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig { @Value("${jdbc.url}")
private String url; @Value("${jdbc.username}")
private String username; @Value("${jdbc.password}")
private String password; @Bean
public MyDriverManager myDriverManager(){
return new MyDriverManager(url, username, password);
} // @Bean(initMethod = "init", destroyMethod = "destroy")// 如果没有指定 name,那么name 为 方法的名称
// public StringStore stringStore() {
// return new StringStore();
// } }

添加测试:

@Test
public void testMyDriverManager() {
MyDriverManager manager = super.getBean("myDriverManager");
System.out.println(manager.getClass().getName());
}

基于泛型的自动装配

示例

新建类:

public class IntegerStore implements Store<Integer> {

}

修改类:

@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig { @Autowired
@Qualifier(value="stringStore")
private Store<String> s1; @Autowired
@Qualifier(value="integerStore")
private Store<Integer> s2; @Bean
public StringStore stringStore() {
return new StringStore();
}
@Bean
public IntegerStore integerStore() {
return new IntegerStore();
} @Bean
public StringStore stringStoreTest(){
System.out.println("s1: " + s1.getClass().getName());
System.out.println("s2: " + s2.getClass().getName());
return new StringStore();
}
}

添加测试:

@Test
public void testG() {
Store store = super.getBean("stringStoreTest");
}

源码:learning-spring

学习 Spring (十) 注解之 @Bean, @ImportResource, @Value的更多相关文章

  1. 学习 Spring (八) 注解之 Bean 的定义及作用域

    Spring入门篇 学习笔记 Classpath 扫描与组件管理 从 Spring 3.0 开始,Spring JavaConfig 项目提供了很多特性,包括使用 java 而不是 XML 定义 be ...

  2. Spring学习(十八)Bean 的三种依赖注入方式介绍

    依赖注入:让调用类对某一接口实现类的依赖关系由第三方注入,以移除调用类对某一接口实现类的依赖.接下来将详细的向大家介绍Spring容器支持的三种依赖注入的方式以及具体配置方法:•    属性注入方法• ...

  3. mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类

    相信大家在刚开始学习mybatis注解方式,或者spring+mybatis注解方式的时候,一定会有一个疑问,为什么mybatis的dao接口只需要一个接口,不需要实现类,就可以正常使用,笔者最开始的 ...

  4. 学习 Spring (九) 注解之 @Required, @Autowired, @Qualifier

    Spring入门篇 学习笔记 @Required @Required 注解适用于 bean 属性的 setter 方法 这个注解仅仅表示,受影响的 bean 属性必须在配置时被填充,通过在 bean ...

  5. Spring通过注解装配Bean

    通过注解实现ServiceImpl业务 一.使用@Component装配Bean 1. 定义类:User 在类上面加@Component注解,在属性上面加@Value值 package com.wbg ...

  6. spring 通过注解装配Bean

    使用注解的方式可以减少XML的配置,注解功能更为强大,它既能实现XML的功能,也提供了自动装配的功能,采用了自动装配后,程序员所需要做的决断就少了,更加有利于对程序的开发,这就是“约定优于配置”的开发 ...

  7. 在Listener(监听器)定时启动的TimerTask(定时任务)中使用Spring@Service注解的bean

    1.有时候在项目中需要定时启动某个任务,对于这个需求,基于JavaEE规范,我们可以使用Listener与TimerTask来实现,代码如下: public class TestTaskListene ...

  8. Spring中注解注入bean和配置文件注入bean

    注解的方式确实比手动写xml文件注入要方便快捷很多,省去了很多不必要的时间去写xml文件 按以往要注入bean的时候,需要去配置一个xml,当然也可以直接扫描包体,用xml注入bean有以下方法: & ...

  9. SpringBoot学习之@Configuration注解和@Bean注解

    @Configuration 1.@Configuration注解底层是含有@Component ,所以@Configuration 具有和 @Component 的作用. 2.@Configurat ...

随机推荐

  1. macOS10.4后的刻盘新姿势

    先sudo -s 输入密码 然后终端拖入createinstallmedia   (在macOS Mojave.app显示包内容里面的resources里面的文件复制下来即可) 输入 --volume ...

  2. Java正则表达式初探(一)

    好多同学们总是听别人说起正则表达式这个东西,也有很多用接触到实际使用过.但是相信有很大一部分人是在用的时候采取网站上搜索,拿一个一知半解的别人写的例子过来,简单测试下功能可用,就OK了.正则表达式那晦 ...

  3. 反射那些基础-Class

    目录 1 Class 类是什么? 2 如何获取 Class 对象 2.1 Object.getClass() 2.2 .class 语法 2.3 Class.forName() 2.4 通过包装类的 ...

  4. 今天我得鼓吹一波 Kotlin

    Kotlin 被作为 Google 官方语言也有一年多了,但除了刚宣布那个月极度火爆以外,后面生活又回归了平静.不少小伙伴紧跟 Google 爸爸的步伐,也对 Kotlin 有了或多或少的了解,Git ...

  5. mysqlfrm

    mysqlfrm可基于frm文件生成对应的表结构.常用于数据恢复场景. 其有两种操作模式. 1. 创建一个临时实例来解析frm文件. 2. 使用诊断模式解析frm文件. 以下表进行测试,看看, 1.  ...

  6. ASP.NET MVC5+EF6+EasyUI 后台管理系统(92)-打印EasyUI 的datagrid表格

    前言 应用系统有时候需要打印Datagrid的表格内容,我们本节就来学习打印datagrid内容 打印主要使用:web打印(我们之前有讲过web打印插件jqprint) + 将datagrid重新编制 ...

  7. Bean笔记

    为什么需要Bean , 因为 Aop 需要. 顺序 InstantiationAwareBeanPostProcessor , BeanPostProcessor 每个Bean都会执行这两个组件的相关 ...

  8. Bootstrap 基础讲解2

    -------------------------------------------思想是行动的先导,心理问题直接作用并影响人的思想. 知识预览 bootstrap简介 CSS栅格系统 四 表格 表 ...

  9. java中scanner的正确用法

    Scanner s = new Scanner(System.in); int choice = 0; if(s.hasNextInt()) { choice = s.nextInt(); } s.c ...

  10. Misha, Grisha and Underground CodeForces - 832D (倍增树上求LCA)

    Misha and Grisha are funny boys, so they like to use new underground. The underground has n stations ...