创建,注册,获取
普通对象
People
接口
package com.cjw.pojo;
public interface People {
void say();
}
Man
类
package com.cjw.pojo;
public class Man implements People{
@Override
public void say() {
System.out.println("I`m Man");
}
}
Woman
类
package com.cjw.pojo;
public class Woman implements People{
@Override
public void say() {
System.out.println("I`m Woman");
}
}
注册
<bean class="com.cjw.pojo.Man"></bean>
<bean class="com.cjw.pojo.Woman"></bean>
获取
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Man bean = ac.getBean(Man.class);
Woman bean2 = ac.getBean(Woman.class);
bean.say();
bean2.say();
}
打印
I`m Man
I`m Woman
环境对象
注册
<beans profile="dev">
<bean class="com.cjw.pojo.Man"></bean>
</beans>
<beans profile="test">
<bean class="com.cjw.pojo.Woman"></bean>
</beans>
测试
@Test
public void test2() {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext2.xml");
ac.getEnvironment().setActiveProfiles("dev");
ac.refresh();
People bean = ac.getBean(People.class);
bean.say();
System.out.println("-----------------------");
ac.getEnvironment().setActiveProfiles("test");
ac.refresh();
bean = ac.getBean(People.class);
bean.say();
}
打印
I`m Man
I`m Woman
工厂对象
PeopleFactory
工厂对象
package com.cjw.pojo;
import javax.annotation.Resource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class PeopleFactory implements FactoryBean<People>, ApplicationContextAware{
private ApplicationContext ac;
@Resource
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ac = applicationContext;
}
@Override
public People getObject() throws Exception {
String[] activeProfiles = ac.getEnvironment().getActiveProfiles();
for (String string : activeProfiles) {
if(string.equals("dev")){
return new Man();
} else if(string.equals("test")){
return new Woman();
} else {
return null;
}
}
return null;
}
@Override
public Class<?> getObjectType() {
return People.class;
}
}
注册
<bean class="com.cjw.pojo.PeopleFactory"></bean>
测试
@Test
public void test3() {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext3.xml");
ac.getEnvironment().setActiveProfiles("dev");
ac.refresh();
People bean = ac.getBean(People.class);
bean.say();
System.out.println("-----------------------");
ac.getEnvironment().setActiveProfiles("test");
ac.refresh();
bean = ac.getBean(People.class);
bean.say();
}
打印
I`m Man
I`m Woman
项目打包 提取码:9qj2
环境:eclipse,maven