观看慕课moocer老师视频Spring Bean装配之Autowire注解说明-6

默认@Bean是单例的,使用@Scope指定它的范围:

package com.imooc.beanannotation.javabased;

//import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Scope;

@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig {

	/*@Value("${url}")
	private String url;
	
	@Value("${jdbc.username}")
	private String username;
	
	@Value("${password}")
	private String password;
	
	@Bean
	public MyDriverManager myDriverManager(){
		return new MyDriverManager(url,username,password);
	}*/
	/*
	@Bean(name="stringStore",initMethod="init",destroyMethod="destroy")
	public Store stringStore(){
		return new StringStore();
	}*/
	
	@Bean(name="stringStore"/*,initMethod="init",destroyMethod="destroy"*/)
	@Scope(value="prototype")
	public Store stringStore(){
		return new StringStore();
	}
}
package com.imooc.test.beanannotation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import com.imooc.beanannotation.javabased.MyDriverManager;
import com.imooc.beanannotation.javabased.Store;
import com.imooc.ioc.interfaces.UnitTestBase;

@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());;
	}
	
	@Test
	public void testMyDriverManager(){
		MyDriverManager manager=super.getBean("myDriverManager");
		System.out.println(manager.getClass().getName());;
	}
	
	@Test
	public void testScope(){
		Store store=super.getBean("stringStore");
		System.out.println(store.hashCode());
		
		store=super.getBean("stringStore");
		System.out.println(store.hashCode());
	}
}

运行结果:

原文链接:加载失败,请重新获取