学习 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 ...
随机推荐
- C学习笔记-一些知识
memset可以方便的清空一个结构类型的变量或数组. 如: struct sample_struct { ]; int iSeq; int iType; }; 对于变量 struct sample_s ...
- Linux进程管理 (1)进程的诞生
专题:Linux进程管理专题 目录: Linux进程管理 (1)进程的诞生 Linux进程管理 (2)CFS调度器 Linux进程管理 (3)SMP负载均衡 Linux进程管理 (4)HMP调度器 L ...
- [LOJ#517]. 「LibreOJ β Round #2」计算几何瞎暴力[trie]
题意 题目链接 分析 记操作异或和为 \(tx\) ,最后一次排序时的异或和为 \(ax\) ,每个数插入时的 \(tx\) 记为 \(b\). 我们发现,一旦数列排序,就会变得容易操作. 对于新加入 ...
- 海纳百川而来的一篇相当全面的Java NIO教程
目录 零.NIO包 一.Java NIO Channel通道 Channel的实现(Channel Implementations) Channel的基础示例(Basic Channel Exampl ...
- 史上最全面的Neo4j使用指南
Neo4j图形数据库教程 Neo4j图形数据库教程 第一章:介绍 Neo4j是什么 Neo4j的特点 Neo4j的优点 第二章:安装 1.环境 2.下载 3.开启远程访问 4.测试 第三章:CQL 1 ...
- A2D Framework - 看如何精简业务逻辑 - 缓存子系统
A2D中一项功能是关于Cache的,能够将判断.获取.删除cache的代码缩减到最少量,如下是Order业务逻辑的demo示范: interface IOrder { [Cachable()] str ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(90)-EF 扩展操作
上一篇讲了EF直接执行SQL与存储过程的用 法 这次我们来看 EntityFramework-Plus(免费开源) 库的用法相比其他扩展库,这个更加新并且用法更加简单 这是一个对Entity Fram ...
- [转]WINDOWS服务器安全加固实战(WINDOWS SERVER 2008 R2和WINDOWS SERVER 2012)
主机安全 启用防火墙 阿里云windows Server 2008 R2默认居然没有启用防火墙.2012可能也是这样的,不过这个一定要检查! 补丁更新 启用windows更新服务,设置为自动更新状态, ...
- python-PyQuery详解
PyQuery库也是一个非常强大又灵活的网页解析库,如果你有前端开发经验的,都应该接触过jQuery,那么PyQuery就是你非常绝佳的选择,PyQuery 是 Python 仿照 jQuery 的严 ...
- 周末时间学习Linux
大家都是如何度过周末时光的呢?好多人都认为一周的工作后要好好休息下,于是在家疯狂的补觉,刷剧,打游戏,自我觉得很是正常,工作几天了,休息下不是当然嘛.是的,休息下很正常,但是把周末的时光都用到这些东西 ...