学习 Spring (十) 注解之 @Bean, @ImportResource, @Value
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的更多相关文章
- 学习 Spring (八) 注解之 Bean 的定义及作用域
Spring入门篇 学习笔记 Classpath 扫描与组件管理 从 Spring 3.0 开始,Spring JavaConfig 项目提供了很多特性,包括使用 java 而不是 XML 定义 be ...
- Spring学习(十八)Bean 的三种依赖注入方式介绍
依赖注入:让调用类对某一接口实现类的依赖关系由第三方注入,以移除调用类对某一接口实现类的依赖.接下来将详细的向大家介绍Spring容器支持的三种依赖注入的方式以及具体配置方法:• 属性注入方法• ...
- mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类
相信大家在刚开始学习mybatis注解方式,或者spring+mybatis注解方式的时候,一定会有一个疑问,为什么mybatis的dao接口只需要一个接口,不需要实现类,就可以正常使用,笔者最开始的 ...
- 学习 Spring (九) 注解之 @Required, @Autowired, @Qualifier
Spring入门篇 学习笔记 @Required @Required 注解适用于 bean 属性的 setter 方法 这个注解仅仅表示,受影响的 bean 属性必须在配置时被填充,通过在 bean ...
- Spring通过注解装配Bean
通过注解实现ServiceImpl业务 一.使用@Component装配Bean 1. 定义类:User 在类上面加@Component注解,在属性上面加@Value值 package com.wbg ...
- spring 通过注解装配Bean
使用注解的方式可以减少XML的配置,注解功能更为强大,它既能实现XML的功能,也提供了自动装配的功能,采用了自动装配后,程序员所需要做的决断就少了,更加有利于对程序的开发,这就是“约定优于配置”的开发 ...
- 在Listener(监听器)定时启动的TimerTask(定时任务)中使用Spring@Service注解的bean
1.有时候在项目中需要定时启动某个任务,对于这个需求,基于JavaEE规范,我们可以使用Listener与TimerTask来实现,代码如下: public class TestTaskListene ...
- Spring中注解注入bean和配置文件注入bean
注解的方式确实比手动写xml文件注入要方便快捷很多,省去了很多不必要的时间去写xml文件 按以往要注入bean的时候,需要去配置一个xml,当然也可以直接扫描包体,用xml注入bean有以下方法: & ...
- SpringBoot学习之@Configuration注解和@Bean注解
@Configuration 1.@Configuration注解底层是含有@Component ,所以@Configuration 具有和 @Component 的作用. 2.@Configurat ...
随机推荐
- 开源版本PowerShell Core 6.2 发布
导读 PowerShell Core 6.2 GA 已发布,PowerShell Core 是 PowerShell 的开源版本,适用于 Linux,macOS 和 Windows. 有关 Power ...
- 20175330 2018-2019-2 《Java程序设计》第八周学习总结
# **教材学习内容总结### 本周学习<Java程序设计>第十五章:*** 泛型: 泛型(Generics)的主要目的是可以建立具有类型安全的集合框架,如链表.散列映射等数据结构.泛型类 ...
- Java多线程核心技术(五)单例模式与多线程
本文只需要考虑一件事:如何使单例模式遇到多线程是安全的.正确的 1.立即加载 / "饿汉模式" 什么是立即加载?立即加载就是使用类的时候已经将对象创建完毕,常见的实现办法就是直接 ...
- 缓存子系统如何设计(Cachable tag, Memcache/redis support, xml config support, LRU/LFU/本地缓存命中率)
大家对这段代码肯定很熟悉吧: public List<UserInfo> SearchUsers(string userName) { string cacheKey=string.For ...
- UART、SPI和I2C详解
做单片机开发时UART,SPI和I2C都是我们最经常使用到的硬件接口,我收集了相关的具体材料对这三种接口进行了详细的解释. UART UART是一种通用串行数据总线,用于异步通信.该总线双向通信,可以 ...
- Spring如何加载log4j配置文件
今天有朋友在群里问了这个问题,于是写了这篇文章进行整理. 问题如下: 在项目中添加了log4j.properties配置文件,并没有在Spring配置文件中配置,也没有在web.xml中配置,但是代码 ...
- RabbitMQ 3.6.1 升级至 3.7.9 版本(Windows 升级至Centos)
随着公司业务量的增加,原本部署在Windows服务器的RabbitMQ集群(3.6.1)总是出现莫名其妙的问题,经查询官方Issue,确认是RabbitMQ 3.6.1 版本的bug.查看从3.6.1 ...
- Python-os模块-60
os 模块: 和操作系统打交道的模块 os模块是与操作系统交互的一个接口 os.makedirs('dirname1/dirname2') 可生成多层递归目录 os.removedirs('dirna ...
- Python_查找员工信息-48
''' 查找出userinfo文件中年龄大于22岁的员工姓名和年龄 1,Alex,22,13651054608,IT 2,Egon,23,13304320533,Tearcher 3,nezha,25 ...
- Rikka with Subset HDU - 6092 (DP+组合数)
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some mat ...