我 的 春天spring 正式开始 !^_^
spring项目基本需要jar->commons-logging.jar;log4j-1.2.9.jar;spring.jar
参考:http://www.redsaga.com/spring_ref/2.0/html/beans.html
本文主要内容:
1.单多配置文件的使用
2.动态替换类方法(cglib)
3.自定义作用域bean
4.定制bean特性
1).单多配置文件的使用1.1)配置文件:beans.xml格式(基本配置)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="userBean" name="userBean"
class="springtest.UserBean"
abstract="false"
singleton="true"
lazy-init="default"
autowire="default"
dependency-check="default" >
<property name="name">
<value>bea</value>
</property>
</bean>
</beans>
spring 工厂建立单配置和多配置文件
//单配置文件加载
public void testSp()throws Exception{
Resource res = new FileSystemResource(
this.getClass().getClassLoader().getResource("config/beans.xml").getPath()
);
BeanFactory fac = new XmlBeanFactory(res);
UserBean uu = (UserBean) fac.getBean("userBean");
System.out.println(uu.getName());
System.out.println(uu.getAge());
}
//多配置文件加载
public void testSps() throws Exception {
ApplicationContext act=new ClassPathXmlApplicationContext(
new String[] {"config/beans.xml",.....}
);
UserBean uu = (UserBean)act.getBean("userBean");
System.out.println( uu.getName());
}
1.2) 还用一种是单配置多<import resource="。.xml"/>达到多配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<import resource="beans_2.xml"/>
<bean id="userBean" name="userBean"
class="springtest.UserBean"
abstract="false"
singleton="true"
lazy-init="default"
autowire="default"
dependency-check="default" >
<property name="name">
<ref bean="str1"/>
</property>
</bean>
</beans>
加载就用上的 -》单配置文件加载
2).动态替换类方法(cglib)配置文件中 替换方法(替换方法
getName ) lib中加入
cglib.jar<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<import resource="beans_2.xml"/>
<bean id="userBean" name="userBean"
class="springtest.UserBean"
abstract="false"
singleton="true"
lazy-init="default"
autowire="default"
dependency-check="default" >
<replaced-method name="getName" replacer="rm">
<arg-type>String</arg-type>
</replaced-method>
<property name="name">
<ref bean="str1"/>
</property>
</bean>
<bean id="rm" class="springtest.ReplacedMethod"/>
</beans>
springtest.ReplacedMethod类
package springtest;
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class ReplacedMethod implements MethodReplacer {
public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable {
return "刘凯毅";
}
}
结果: 不管你怎么setName getName出来的都是-》 “刘凯毅”
3.自定义作用域bean 需要jdk1.5
4.定制bean特性
1)初始化回调 <bean id=".." class=".." init-method="init"/> 方法init()
和 继承
org.springframework.beans.factory.InitializingBean 实现接口方法
void afterPropertiesSet() throws Exception; 一样
2)