一、Spring基础应用
SpringMVC:
web.xml
<servlet>
<servlet-name>springCms</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springCms-servlet-admin.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springCms</servlet-name>
<url-pattern>*.admin</url-pattern>
</servlet-mapping>
其他Web环境:
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/webContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ApplicationContextctx=new ClassPathXmlApplicationContext(“appContext.xml”);
ApplicationContextctx=new ClassPathXmlApplicationContext(newString[]{“1.xml”,“2.xml”});
ctx.getBean(“beanid”);
ApplicationContextctx=new FileSystemXmlApplicationContext(“appContext.xml”);
在程序的运行过程中,如果需要另外的对象协作时,无须在代码中创建被调用者,而是依赖于外部容器的注入,包括:
设值注入(setter方法)
<beanid=“id” class=“类全名”>
<property name=“属性名” value/ref=“值/id”/>
</bean>
构造注入(构造方法)
<beanid=“id” class=“类全名”>
<constructor-arg value/ref=“值/id”/>
</bean>
ApplicationContextctx=new FileSystemXmlApplicationContext(newString[]{“1.xml”, “2.xml”});
ctx.getBean(“beanid”);
资源文件名:
messages.properties; messages_en_US.properties, messages_zh_CN.properties
<bean id="messageSource"class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<propertyname="basenames">
<list>
<value>classpath:messages</value>
</list>
</property>
</bean>
String hello=ctx.getMessage(“key”,new String[]{“b”},Locale.getDefault());
<bean/>元素基本语义
id:bean的标识
name:bean的名称,可用逗号、冒号、空格分隔多个名称
class:类的全名
abstract=false:抽象父类
parent:父类id
autowire:自动装配,可选byName/byType/constructor/autodetect/no(默认)
autowire-candidate=false:不参加自动装配
primary=false:首选自动装配
init-method:指定初始化方法,public void XX();
destroy-method:指定销毁方法,public void XX();
lazy-init=false:延迟初始化
scope:bean的作用域,可选singleton(默认)/prototype/request/session
depends-on:依赖的bean
factory-bean:指定构造工厂bean
factory-method:指定构造工厂方法
ApplicationContext事件
事件定义:
extends ApplicationEvent
发布事件:
ctx.publishEvent();
事件监听:
implements ApplicationListener
<bean id="listener"class="test.ContainerEventListener"/>
内置事件:
<constructor-arg type=“java.lang.String” value/ref=“hello”index/name=""/>
<ref bean="someBean"/>&<ref local="someBean"/>
<props value-type="java.lang.String">
<prop key="test">testvalue</prop>
</props>
<list value-type="java.lang.String">
<value>value</value>
</list>
<map key-type=""value-type="">
<entry key="" value/value-ref=""/>
</map>
<set value-type="">
<value>value</value>
</set>
二、Spring高级应用
Spring容器扩展
Bean后处理器
BeanPostProcessor
public Object postProcessBeforeInitialization(Object bean, String beanName)
public Object postProcessAfterInitialization(Object bean, String beanName)
容器后处理器
BeanFactoryPostProcessor
public void postProcessBeanFactory(ConfigurableListableBeanFactoryctx)
在容器初始化完成Bean创建之前处理
使用参数化配置文件
<context:property-placeholder location="classpath:hibernate.properties"/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname="locations"><value>classpath:com/foo/jdbc.properties</value>
</property>
</bean>
<bean class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"value="${jdbc.driverClassName}"/> </bean>
常用注解支持
<context:component-scanbase-package="zxb.modules"/>
@Component("beanName")组件
@Controller("beanName")控制器
@Service("beanName")服务
@Repository("beanName")DAO
@Lazy(boolean)延迟初始化
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
@Resource(name="beanName")setter方法前或field前
@Autowired()setter方法前或field前,默认byType
@Qualifier("beanName")与@Autowired精确指定自动装配,可修饰形参
@PostConstruct标注初始化方法
@PreDestroy标注销毁方法
AOP基本概念
<aop:config>
<aop:pointcut expression="execution(*zxb.annotation.*.* (..))" id="out"/>
<aop:aspect ref="aspect">
<aop:pointcut expression="execution(*zxb.annotation.*.* (..))" id="in"/>
<aop:before method="before"pointcut-ref="in"/>
<aop:after method="after"pointcut-ref="out"/>
<aop:after-returning method="afterReturning"returning="returnValue"pointcut-ref="out"/>
<aop:after-throwing method="afterThrowing"throwing="ex" pointcut-ref="out"/>
<aop:around method="around"pointcut-ref="out"/>
</aop:aspect>
</aop:config>
三、Spring+Hibernate高级应用
Spring定时调度服务(注解)
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler"pool-size="10"/>
<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<context:component-scan base-package="zxb.modules" annotation-config="true" />
@Scheduled(fixedRate=3000)
public void testTask(){
System.out.println("scheduled");
}
fixedRate:每隔fixedRate毫秒调用一次
fixedDelay:方法结束后隔fixedDelay毫秒调用一次
cron:时间表达式
Spring定时调度服务(XML)
<beanid="job"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject"ref=“userManagerProxy"/>
<property name="targetMethod"value=“testTask"/>
</bean>
<bean id="triggerBean"class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail"ref="job"/>
<property name="startDelay"value=“3000"/>
<property name="repeatInterval"value=“5000"/>
</bean>
<bean id="cronTrigger"class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail"ref="job"/>
<property name="cronExpression"value="59 59 23 * * ?" />
</bean>
<bean id=“schedulerFactoryBean"class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<propertyname="triggers">
<list>
<reflocal="triggerBean"/>
</list>
</property>
</bean>
Spring基于HTTP的远程访问
web.xml
<servlet>
<servlet-name>imtiService</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/imtiService-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>imtiService</servlet-name>
<url-pattern>*.service</url-pattern>
</servlet-mapping>
Spring基于HTTP的远程访问
服务端:
<bean name="/userManager.service"class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<propertyname="service" ref=“userManagerProxy"/>
<propertyname="serviceInterface" value="imti.module.cms.ICmsManager"/>
</bean>
客户端:
<bean id="remoteUserManagerService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<propertyname="serviceUrl" value="${remoteUserService.httpServiceUrl}"/>
//http://127.0.0.1:8080/imtiService/userManager.service
<propertyname="serviceInterface" value="imti.module.user.IUserManager"/>
</bean>
Spring-访问JNDI对象
<bean id="dataSource"class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="lookupOnStartup">
<value>true</value>
</property>
<propertyname="cache">
<value>true</value>
</property>
<propertyname="expectedType">
<value>javax.sql.DataSource</value>
</property>
<propertyname="jndiName">
<value>java:comp/env/jdbc/MyDataSource</value>
</property>
</bean>
基于Spring的集成测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:baseContext.xml")
@Transactional//事务配置
public class TestUserManager{…}
@Resource(name="userManager")
private IUserManageruserManager;
@Test
@Rollback(false)//覆盖类事务设置,是否回滚
@Repeat(1)//重复执行次数
@NotTransactional//不使用事务
public void testAddUser() {…}
Hibernate综合查询
User user=new User();
user.setUserName("userName");
Criteria criteria = session.createCriteria(User.class);
criteria.add(Example.create(user).enableLike(MatchMode.ANYWHERE));
return criteria.list();