spring容器中bean的作用域bean的后处理器

容器bean中的作用域

applicationcontext.xml




    
    

接口:

public interface ISomeService {
	void doSome();
}
工厂类:
public class ServiceFactory {
	public static ISomeService getSomeService() {
		return new SomeServiceImpl();
	}
}


 
  
实现类:

public class SomeServiceImpl implements ISomeService {
	private int a;
	
	public SomeServiceImpl() {
		System.out.println("执行无参构造器");
	}
	
	/*
	public SomeServiceImpl(int a) {
		this.a = a;
	}
	*/
	
	@Override
	public void doSome() {
		System.out.println("执行doSome()方法");
	}


}
测试类

public class MyTest {
	
	@Test
	public void test01() {
		// 创建容器对象,加载Spring配置文件
		String resource = "com/bjpowernode/ba03/applicationContext.xml";
		ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
		ISomeService service = (ISomeService) ac.getBean("myService");
		service.doSome();
	}
	
}

后处理器:

applicationcontext.xml




    
    
    
    
    
    


处理器类:

通过处理改变输出字母的大小写

public class MyBeanPostProcessor implements BeanPostProcessor {

	// bean:表示当前正在进行初始化的Bean对象
	// beanName:表示当前正在进行初始化的Bean对象的id
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		System.out.println("执行 ----before---()方法");
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(final Object bean, String beanName)
			throws BeansException {
		System.out.println("执行 ----after---()方法");
		if ("myService".equals(beanName)) {
			Object obj = Proxy.newProxyInstance(bean.getClass()
					.getClassLoader(), bean.getClass().getInterfaces(),
					new InvocationHandler() {

						@Override
						public Object invoke(Object proxy, Method method,
								Object[] args) throws Throwable {
							Object invoke = method.invoke(bean, args);
							if ("doSome".equals(method.getName())) {
								return ((String) invoke).toUpperCase();
							}
							return invoke;
						}
					});
			return obj;
		}
		return bean;
	}

}

接口类

public interface ISomeService {
	String doSome();
	String doOther();
}
实现类

public class SomeServiceImpl implements ISomeService {
	
	@Override
	public String doSome() {
		System.out.println("执行doSome()方法");
		return "abcde";
	}
	
	@Override
	public String doOther() {
		System.out.println("执行doOther()方法");
		return "fghig";
	}


}

测试类:

public class MyTest {
	
	@Test
	public void test01() {
		// 创建容器对象,加载Spring配置文件
		String resource = "com/bjpowernode/ba05/applicationContext.xml";
		ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
		
		ISomeService service = (ISomeService) ac.getBean("myService");
		System.out.println(service.doSome());
		System.out.println(service.doOther());
		
		System.out.println("======================");
		
		ISomeService service2 = (ISomeService) ac.getBean("myService2");
		System.out.println(service2.doSome());
		System.out.println(service2.doOther());
	}
	
}





你可能感兴趣的:(spring)