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. Mybatis学习总结(五)——动态sql

    MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉 ...

  2. 使用webstrom开发react-native时react-native代码会出现红色下划线的解决方法

    问题:使用webstrom开发react-native时react-native代码会出现红色下划线的解决方法 解决方法:webstrom ->preferences->Laugrange ...

  3. 实时监控input输入值变化

    在web开发中,我们有时会需要动态监听输入框值的变化,当使用onkeydown.onkeypress.onkeyup作为监听事件时,会发现一些复制粘贴等操作用不了,同时,在处理组合快键键的时候也很麻烦 ...

  4. 基于Vue.js 2.0 + Vuex打造微信项目

    一.项目简介 基于Vue + Vuex + Vue-router + Webpack 2.0打造微信界面,实现了微信聊天.搜索.点赞.通讯录(快速导航).个人中心.模拟对话.朋友圈.设置等功能. 二. ...

  5. FineUI经典项目展示(1)生产在线管理系统

    本系列<FineUI经典项目展示>文章将会集中展示一批使用FineUI(开源版).专业版.MVC版的经典项目. 如果你希望自己的FineUI项目出现在这个舞台,请到官网论坛提交申请: ht ...

  6. Javascript设计模式之我见:观察者模式

    大家好!本文介绍观察者模式及其在Javascript中的应用. 模式介绍 定义 定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并被自动更新. 类图及说明 S ...

  7. 异步时代-java的协程路在何方

    面试官:你知道协程吗? 你:订机票的那个吗,我常用. 面试官:行,你先回去吧,到时候电话联系 ........ 很尴尬,但是事实是,很大一部分的程序员不知道协程是啥玩意,更大一部分的程序员,项目中没用 ...

  8. js判断当前浏览器页面是否切换

    公司做mifi设备,ui界面很多信息需要1S钟不断异步请求更新信息,如果同时打开多个浏览器或者多个当前界面,设备1S钟会收到很多个请求,由于设备本身内存限制,会导致响应速度过慢,且会造成设备重启等. ...

  9. Python-os模块-60

    os 模块: 和操作系统打交道的模块 os模块是与操作系统交互的一个接口 os.makedirs('dirname1/dirname2') 可生成多层递归目录 os.removedirs('dirna ...

  10. Django之ORM操作(聚合 分组、F Q)

    Django之ORM操作(聚合 分组.F Q) 聚合 aggregate()是QuerySet的一个终止子句,也就是说,他返回一个包含一些键值对的字典,在它的后面不可以再进行点(.)操作.   键的名 ...