基本配置
1 导入相应的jar文件
2 创建xml文件(通过拷贝)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<beanid="roleDao"class="org.itfuture.www.dao.Imp.RoleDaoImp"/>
</beans>
Beans的基本管理
读取配置xml文件
方式一(推荐使用方法)
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext-*");
方式二
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext-daos.xml,applicationContext-services.xml");
实例化对象
RoleDao roledao=(RoleDao) ctx.getBean("roleDao");或
//此方式Spring3.0以上支持
RoleService roleService=ctx.getBean("roleService", RoleServcie.class);
RoleService roleService=ctx.getBean(RoleServcie.class);
实例的唯一性
scope="singleton":表示实例是唯一的,默认情况下实例唯一
scope="prototype":表示实例不是唯一的,每次创建都会产生新的实例
如:
<beanid="roleDao"class="org.itfuture.www.dao.Imp.RoleDaoImp"scope="prototype"/>//表示每创建实例不是唯一的
延迟加载
lazy-init=”true”默认情况下为不延迟加载,当为false时延迟加载
<beanid="roleDao"class="org.itfuture.www.dao.Imp.RoleDaoImp"lazy-init="false"/>//表示不延迟加载
提前初始化
init-method="方法名":表示提前初始化方法中的内容
destory-method :表示销毁
<beanid="roleService"class="org.itfuture.www.service.Imp.RoleServcieImp"init-method="init"/>//表示提前初始化方法中的内容
静态工厂与实例工厂的配置
(1)静态工厂配置
<beanid="roleService"class="org.itfuture.www.util.ServiceFactory"factory-method="getRoleService"/>
(2)实例工厂配置
<beanid="serviceFactory"class="org.itfuture.www.util.ServiceFactory"/><!—先实例化工厂-->
<beanid="roleService"factory-bean="serviceFactory"factory-method="getRoleService"/>
注释编程
配置:在配置文件头部中添加相应的命名空间地址(通过拷贝)
xmlns:context=http://www.springframework.org/schema/context
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
<context:component-scanbase-package="org.itfuture.www.service,org.itfuture.www.dao"/>
注:会自动加载前缀为org.itfuture.www.service和org.itfuture.www.dao的包
使用@Componnet注解标识该类运行被Sprig容器管理,默认Bean名称返回小写字母开头的非限定名。也可自定义名称@Componnet(“roleDao”)
如:@Component("roleDao")
publicclass RoleDaoImpimplements RoleDao {
}
在使用注释时可以将其细化@Repository(持久层)@Service(服务层)@Controller(表现层)
注释实例化
@Service("UserService")
publicclass UserServiceImpimplements UserService {
}
进行实例化
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService=(UserService)ctx.getBean("UserService");
注:如果@Service没有自定义名称默认为该类名称首字母小写开头,可以通过getBean("userService")
实例的唯一性与延迟加载
@Repository("UserDao")
@Scope("prototype")//实例不唯一
@Lazy(false)//不延迟加载
publicclass UserDaoImpimplements UserDao {
}
依赖注入
Spring中注入方式有接口注入、构造注入、方法注入、属性注入
bean实例注入(推荐使用方法注入)
方式一Set方法注入
<beanid="roleService"class="org.itfuture.www.service.Imp.RoleServcieImp">
<propertyname="roleDao"ref="roleDao"/>
</bean>
注:name为javaBean中的set方法名,ref为Bean中id的值
方式二构造方式注入
<beanid="userService"class="org.itfuture.www.service.Imp.UserServiceImp">
<constructor-argref="userDao"/>
</bean>
或者(此方式不推荐)
<beanid="userService"class="org.itfuture.www.service.Imp.UserServiceImp">
<constructor-arg>
<refbean="userDao"/>//当bean在一个配置文件中时也可以通过<ref local=”userDao”>
</constructor-arg>
</bean>
基本类型注入
方式一Set方法注入
<beanid="person"class="org.itfuture.www.model.Person">
<propertyname="id"value="1"/>
<propertyname="name"value="Tom"/>
<propertyname="sex"value="M"/>
<propertyname="age"value="20"/>
</bean>
方式二构造注入
<beanid="person"class="org.itfuture.www.model.Person">
<constructor-argname="id"value="1"/>
<constructor-argname="name"value="Lily"/>
<constructor-argname="sex"value="W"/>
<constructor-argname="age"value="21"/>
</bean>
集合容器注入
List容器注入
<propertyname="school">
<list>
<value>A</value>
<value>B</value>
</list>
</property>
Set容器注入
<propertyname="teacher">
<set>
<value>a</value>
<value>b</value>
</set>
</property>
Map容器注入
<propertyname="scores">
<map>
<entrykey="高数"value="80"/>
<entrykey="英语">
<value>65</value>
</entry>
</map>
</property>
Properties容器注入
<propertyname="col">
<props>
<propkey="a">1</prop>
<propkey="b">2</prop>
</props>
</property>
注:也可通过构造方式注入
编辑器
publicvoid setAsText(String text)throws IllegalArgumentException {
DateFormat df = new SimpleDateFormat(pattern);
if(text ==null ||"".equals(text)){
this.setValue(null);
return;
}
try {
Date date = df.parse(text);
this.setValue(date);
} catch (ParseException e) {
thrownew IllegalArgumentException(e);
}
}
配置
<beanid="customEditorConfigure"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<propertyname="customEditors">
<map>
<entrykey="java.util.Date">
<bean
class="org.itfuture.util.propertyeditor">
<propertyname="pattern"value="yyyy-MM-dd"/>
</bean>
</entry>
</map>
</property>
</bean>
@Autowired注解实现自动和精确装配
Spring提供了@Autowired注解来指定自动装配,此注解可以标注在方法、属性和构造方法等
1 默然情况下。它要求对象必须存在,如果允许为null值,可以设置required的属性为false(如:@Autowired(required=false)),默认情况下为true
2 如果想使用按照名称装配,可以结合@Qualifier注解一起使用(如:@Qualifier(“roleDao”))
使用注解时候需要在xml中进行配置,读取相应的包
如:
@Service
publicclass UserServiceImpimplements UserService {
private UserDaouserDao;
@Autowired
@Qualifier(“roleDao”)//当使用自定义名称时,要注入的类也必须自定名称
publicvoid setUserDao(UserDao userDao) {
this.userDao = userDao;
}
Resources注解
@Service
publicclass UserServiceImpimplements UserService {
private UserDaouserDao;
@Resource(name=”userDao”)
publicvoid setUserDao(UserDao userDao) {
this.userDao = userDao;
}
使用P命名空间设置属性
配置文件需要导入xmlns:p=http://www.springframework.org/schema/p
可以通过P命名空间获取资源文件
<beanid="dateSource"class="org.apache.commons.dbcp.BasicDataSource"
p:driverClassName="com.mysql.jdbc.Driver"p:url="jdbc:mysql:///test"
p:username="root"
p:password="root"/>
可通过引用
<beanid="roleDao"class="org.itfuture.www.dao.Imp.RoleDaoImp"p:dateSource-ref="dateSource"/>
引用
<beanid="roleService"class="org.itfuture.www.service.Imp.RoleServcieImp"p:roleDao-ref="roleDao"/>
抽离的方式
<beanabstract="true"id="daoSupport" p:dataSource-ref="dataSource"/>
<beanid="roleDao"class="org.itfuture.www.dao.Imp.RoleDaoImp"parent=" daoSupport "/>
自动装配依赖对象(不推荐使用)
注入依赖对象可采用手动或自动,在实际运用中建议采用手动装配
Autowire=”byName|byType|constructor|autodetect”
byName:按照名字一次装配。可以根据属性名称,在容器中寻找跟该属性名字相同的Bean如果没找到返回null
byType:按照类型装配,可以根据属性类型,在容器中寻找跟该属性类型相同的Bean,如果出现多个将出向异常,没有返回null
constructor:与byType类时,不同之处它应用于构造参数,如果没有找到与构造参数类型一致的Bean,将抛出异常
如:
<beanid="userDao"class="org.itfuture.www.dao.impl.userDaoImp"autowire="byName"/> <!--默认在spring容器中寻找setDataSource对应的dataSource名称 -->
<beanid="roleDao"class="org.itfuture.www.dao.impl.roleDaoImpl"autowire="byType/constructor"/>
Util(3.0支持)(不推荐使用)
配置xml
xmlns:util="http://www.springframework.org/schema/util"
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"
如:
<util:listid="schools"list-class="java.util.LinkedList"
value-type="java.lang.String">
<value>A</value>
<value>B</value>
</util:list>
<beanid="person"class="org.itfuture.examples.model.Person">
<propertyname="schools"ref="schools"/>
</bean>
占位符
读取properties文件方式一
<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname="locations">
<list>
<value>classpath:config1.properties</value>
<value>classpath:config2.properties</value>
/*以通过通配来配置
<value>classpath:config*.properties</value>*/
</list>
</property>
</bean>
读取properties文件方式二
<context:property-placeholderlocation="classpath:config1.roperties,classpath:config2.poperties”/>0
/*或者
<context:property-placeholder location="classpath:config*.properties" />*/
占位方式
<beanid="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"
p:driverClassName="${driverClassName}"p:url="${url}"
p:username="${username}"
p:password="${password}"/>
<value>classpath:config1.properties</value>
<value>classpath:config2.properties</value>
/*以通过通配来配置
<value>classpath:config*.properties</value>*/
</list>
</property>
</bean>
Spring管理整合Struts
Web项目中实例化Spring容器
方式一:
在Sturts配置文件配置
<actionpath="/system/user" parameter="command"
type="org.springframework.web.struts.DelegatingActionProxy">
</action>
<plug-inclassName="org.springframework.web.struts.ContextLoaderPlugIn">
<set-propertyproperty="contextConfigLocation"value="classpath:applicationContext-*.xml"/>
</plug-in>
方式二:
在web.xml中配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
AOP代理
方式一:注解方式实现AOP
1 创建一个代理类
2 配置文件中进行配置
<context:component-scanbase-package="org.itfuture.www"/>
<aop:aspectj-autoproxy/>
3 在代理类中进行注解
//定义一个切入点
@Pointcut("execution(* org.itfuture.www.service..*.*(..))")
privatevoid any(){
}
//环绕通知
@Around("any()")
public Object arround(ProceedingJoinPoint pjp)throws Throwable{
System.out.println("开始!");
Object obj=pjp.proceed();//相当于执行了被代理真实方法
System.out.println("结束!");
return obj;
}
//分别进行通知(不推荐使用)
@Before("any()")
publicvoid before(){
System.out.println("前置通知!");
}
@AfterReturning("any()")
publicvoid after(){
System.out.println("后置通知!");
}
@AfterThrowing("any()")
publicvoid doThrow(){
System.out.println("异常通知!");
}
@After("any()")
publicvoid end(){
System.out.println("最终通知!");
}
方式二:通过配置xml文件进行代理
<beanid="log"class="org.itfuture.www.aop.Log"/>
<aop:config>
<aop:aspectid="aop"ref="log">
<aop:pointcutid="any" expression="execution(* org.itfuture.www.service..*.*(..))"/>
<!--<aop:before method="before" pointcut-ref="any"/>
<aop:after-returning method="after" pointcut-ref="any"/>
<aop:after-throwing method="doThrow" pointcut-ref="any"/>
<aop:after method="end" pointcut-ref="any"/>-->
<aop:aroundmethod="around"pointcut-ref="any"/>
</aop:aspect>
</aop:config>