Spring入门——基于Java的容器注解说明之@bean

基于Java的容器注解

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

可以在Spring的@Component注解的类中使用@Bean注解任何方法(仅仅是可以)

上一点中,通常使用的是@Configuration



例子:

创建一个接口Store,和一个实现类StringStore什么都不用做只需创建,然后再创建一个StoreConfig类

StoreConfig类

package com.txr.beanannotation.javabased;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SroreConfig {
	
	@Bean(name="store")
	public Store getStringStore()
	{
		return (Store) new StringStore();
	}

}

测试:

@Test
	public void test()
	{
		Store store=(Store) context.getBean("store");
		System.out.println(store.getClass().getName());
	}

测试结果:

com.txr.beanannotation.javabased.StringStore

补充:当@Bean没有指定name时生成的Bean id标识默认为首字母小写的方法名如在这为getStringStore

测试init 与destroy

StoreConfig

package com.txr.beanannotation.javabased;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SroreConfig {
	
	@Bean(name="store" ,initMethod="init",destroyMethod="destroy")
	public Store getStringStore()
	{
		return (Store) new StringStore();
	}

}
在StringStore中添加方法名为init与destory的方法

package com.txr.beanannotation.javabased;

public class StringStore implements Store{
	public void init()
	{
		System.out.println("this is init");
	}
	public void destroy()
	{
		System.out.println("this is destroy");
	}
}
测试结果

this is init
com.txr.beanannotation.javabased.StringStore
this is destroy







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值