J2EE轻量级架构与企业级应用开发
2013-10-31 09:10
429 查看
一、Spring基础应用
1、低侵入式设计
2、应用服务器独立
3、DI(DependencyInjection)依赖注入容器、对象工厂
4、AOP(AspectOrient Programming)容器,更好的复用
5、主流框架的整合
6、优秀的Web MVC框架
7、简化的任务调度、远程访问、Mail等企业级服务
Web环境启动:
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>
非Web环境启动:
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"/>
内置事件:
•ContextRefreshedEvent (容器初始化或.refresh()后)
•ContextStartedEvent (容器.start()方法)
•ContextStoppedEvent (容器.stop()方法)
•ContextClosedEvent (容器停止.registerShutdownHook())
•RequestHandledEvent(DispatcherServlet容器中请求结束)
常用注入配置:
<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"
4000
>
<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:面向切面编程,OOP中模块单元是类,AOP模块单元是切面
•切面(Aspect):程序运行过程中关注点的模块化
•连接点(JoinPoint):在程序执行过程中某个特定的点,比如某方法调用的时候或者处理异常的时候。在SpringAOP中,一个连接点总是表示一个方法的执行
•通知(Advice):在连接点执行的动作,包括了“around”、“before”和“after”等不同类型的通知
•切入点(Pointcut):匹配连接点的条件,Spring缺省使用AspectJ切入点语法
•引入(Introduction):把方法或属性添加的被处理的类中
•目标对象(Target Object):被增强处理的对象
•AOP代理(AOP Proxy):AOP框架创建的对象,Spring中,AOP代理可以是JDK动态代理(接口)或者CGLIB(类)代理,默认使用JDK动态代理
•织入(weaving):把切面连接到其它的应用程序类型或者对象上,并创建一个被通知的对象。包括编译时织入(Aspectj)和运行时织入(CGLIB)
Spring的AOP-XML配置
<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();
1、低侵入式设计
2、应用服务器独立
3、DI(DependencyInjection)依赖注入容器、对象工厂
4、AOP(AspectOrient Programming)容器,更好的复用
5、主流框架的整合
6、优秀的Web MVC框架
7、简化的任务调度、远程访问、Mail等企业级服务
Web环境启动:
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>
非Web环境启动:
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"/>
内置事件:
•ContextRefreshedEvent (容器初始化或.refresh()后)
•ContextStartedEvent (容器.start()方法)
•ContextStoppedEvent (容器.stop()方法)
•ContextClosedEvent (容器停止.registerShutdownHook())
•RequestHandledEvent(DispatcherServlet容器中请求结束)
常用注入配置:
<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"
4000
>
<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:面向切面编程,OOP中模块单元是类,AOP模块单元是切面
•切面(Aspect):程序运行过程中关注点的模块化
•连接点(JoinPoint):在程序执行过程中某个特定的点,比如某方法调用的时候或者处理异常的时候。在SpringAOP中,一个连接点总是表示一个方法的执行
•通知(Advice):在连接点执行的动作,包括了“around”、“before”和“after”等不同类型的通知
•切入点(Pointcut):匹配连接点的条件,Spring缺省使用AspectJ切入点语法
•引入(Introduction):把方法或属性添加的被处理的类中
•目标对象(Target Object):被增强处理的对象
•AOP代理(AOP Proxy):AOP框架创建的对象,Spring中,AOP代理可以是JDK动态代理(接口)或者CGLIB(类)代理,默认使用JDK动态代理
•织入(weaving):把切面连接到其它的应用程序类型或者对象上,并创建一个被通知的对象。包括编译时织入(Aspectj)和运行时织入(CGLIB)
Spring的AOP-XML配置
<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();
相关文章推荐
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- 利用 J2EE 连接器架构和 SOAP 构建“Web服务就绪”的企业级应用
- Eclipse/TomCat上的J2EE应用开发软件架构4
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- Eclipse/TomCat上的J2EE应用开发软件架构4
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- 纪念日:服务构件环境(SCE)挑起企业级架构的栋梁,下一代的应用开发模式日渐清晰
- J2EE 企业级应用架构简述
- BEA成都User Group活动-J2EE应用架构设计和开发
- 基于J2EE轻量级架构的多层应用的研究
- J2EE架构企业级应用
- J2EE企业级应用架构发展
- J2EE企业级应用架构简述
- ThreadLocal在J2EE轻量级开发中的应用
- 基于struts+spring+ibatis的轻量级J2EE开发
- 企业级搜索应用服务器Solr4.10.4部署开发详解(2)- Solr使用-创建集合表、存储、查询