经过测试之后用注解的方式 不行 所以只能采用容器取的方式。例子代码如下
package com.dragon.service.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component("testBean")
@Scope("singleton")
public class TestBean {
<span style="white-space:pre"> </span>//@Autowired
<span style="white-space:pre"> </span>//private TestBean1 testBean1;
public TestBean1 getTestBean1() {
return (TestBean1) SpringBeanUtils.getBean("testBean1");
}
}
package com.dragon.service.test;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component("testBean1")
@Scope("prototype")
public class TestBean1 {
private Integer num = 1;
public Integer getNum() {
num++;
return num;
}
}
package com.dragon.service.test;
import java.util.Map;
import org.slf4j.*;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
@Service
public class SpringBeanUtils implements ApplicationContextAware {
private static ApplicationContext appContext;
private Logger logger = LoggerFactory.getLogger(getClass());
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringBeanUtils.appContext = applicationContext;
logger.debug("初始化Spring上下文成功。");
}
/**
* 获取 ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return appContext;
}
/**
* 获取 TestBean
*
* @param beanName
* bean 名称
* @return
*/
public static Object getBean(String beanName) {
checkApplicationContext();
return appContext.getBean(beanName);
}
/**
* 获取 TestBean
*
* @param clazz
* bean 类
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
Map<?, ?> map = appContext.getBeansOfType(clazz);
return map.isEmpty() ? null : (T) map.values().iterator().next();
}
/**
* 检查 ApplicationContext 是否注入
*/
private static void checkApplicationContext() {
if (null == appContext) {
throw new IllegalStateException("applicaitonContext未注入");
}
}
}
测试类如下
package com.dragon.test;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.dragon.service.test.TestBean;
public class TestBeanTest extends BaseTest {
@Autowired
private TestBean testBean1;
@Autowired
private TestBean testBean2;
@Test
public void testAdd() {
System.out.println(testBean1.getTestBean1().getNum());
System.out.println(testBean2.getTestBean1().getNum());
}
}
这样子输出的结果是 2,2 也就说明了 每次取到的testbean1对象都是新的对象
如果testbean里面采用注入的方式 打印的结果是2,3