Spring的XML配置文件的十二个最佳方法实践

合集下载

Spring配置定时器(注解+xml)方式—整理

Spring配置定时器(注解+xml)方式—整理

Spring配置定时器(注解+xml)⽅式—整理⼀、注解⽅式1. 在Spring的配置⽂件ApplicationContext.xml,⾸先添加命名空间1 xmlns:task="/schema/task"2 /schema/task3 /schema /task/springtask3.1.xsd42. 最后是我们的task任务扫描注解1<task:annotation-driven/>3. spring扫描位置1<context:annotation-config/>2<context:component-scan base-package="com.test"/>4.写⾃⼰的定时任务1 @Component //import ponent;2public class MyTestServiceImpl implements IMyTestService {3 @Scheduled(cron="0/5 * * * * ? ") //每5秒执⾏⼀次4public void myTest(){5 System.out.println("进⼊测试");6 }7 }♦注意:定时器的任务⽅法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定⼀个proxytargetclass的某个值为true)⼆、XML⽅式1.在spring配置⽂件中创建bean,创建schedule1<bean id="schedule"class="org.springframework.scheduling.quartz.SchedulerFactoryBean">3<property name="triggers">4<list>5<ref bean="testTrigger"/>6</list>7</property>8</bean>2. 在spring配置⽂件中创建bean,创建你的triggers1<bean id="testTrigger"class="org.springframework.scheduling.quartz.CronTriggerBean">3<property name="jobDetail" ref="testJobDetail"/>4<property name="cronExpression" value="0 1/5 * * * ?"/>5</bean>3. 在spring配置⽂件中创建bean,指定定时器作⽤在那个类那个⽅法上⾯1<bean id="testJobDetail"class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">3<property name="targetObject" ref="targetTestService"/>4<property name="targetMethod" value="timerTest"/>5</bean>♦注明:把定时器作⽤在targetTestService对象中的timerTest⽅法上⾯4. 当然还得把你作⽤的对象交Spring来管理,所以在spring配置⽂件中创建作⽤类的 bean1<bean id="targetTestService" class=".service.TargetTestService" scope="prototype"></bean>♦这是时间的设置规则org.springframework.scheduling.quartz.CronTriggerBean允许你更精确地控制任务的运⾏时间,只需要设置其cronExpression属性。

springmvc框架搭建之xml配置说明(spring4+hibernate4)

springmvc框架搭建之xml配置说明(spring4+hibernate4)

SpringMVC框架搭建说明Spring4.1.4 + hibernate4.3.81、web.xml配置程序运行时从web.xml开始,加载顺序为:context-param -> listener -> filter ->structs (如果使用structs的话)-> servlet如下为web.xml的配置说明<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance"xmlns="/xml/ns/javaee"xmlns:web="/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><!—-显示项目名称--><display-name>bmymis2</display-name><!-- 指定配置文件位置,contextConfigLocation是ContextLoaderListener中的一个参数,通过该参数在ContextLoaderListener中加载applicationContext-*.xml,并装配ApplicationContext --> <context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext-*.xml</param-value></context-param><!-- 定义SPRING监听器,启动Web容器时,自动装配ApplicationContext的配置信息--><listener><listener-class>org.springframework.web.context.ContextLoaderListener </listener-class></listener><!—-字符编码过滤器,解决中文乱码问题--><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><!—- springmvc配置--><servlet><servlet-name>springServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath*:/spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup> //容器启动时首先初始化该servlet </servlet><servlet-mapping><servlet-name>springServlet</servlet-name><url-pattern>/</url-pattern> //表示所有页面都由springmvc处理</servlet-mapping><!—-浏览器输入到项目名,默认打开如下配置页面--><welcome-file-list><welcome-file>/web/login.jsp</welcome-file></welcome-file-list><!—-错误跳转页面--><error-page><error-code>404</error-code><location>/404.html</location></error-page></web-app>2、applicationContext-common.xml配置:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:context="/schema/context"xmlns:xsi="/2001/XMLSchema-instance"xmlns:tx="/schema/tx"xmlns:aop="/schema/aop"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-4.0.xsd/schema/context/schema/context/spring-context-4.0.xsd/schema/aop/schema/aop/spring-aop-4.0.xsd/schema/tx/schema/tx/spring-tx-4.0.xsd"><!-- 加载资源文件其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载--><context:property-placeholder location="classpath:application.properties"/><!—-扫描包路径选项,使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入,有了该配置,那么<context:annotation-config/>这个配置就可以省略(以下配置包含了<context:annotation-config/>配置)--><context:component-scan base-package="xxx.xxx.xxx"/><!-- 数据源配置,使用应用内的DBCP数据库连接池 --><bean id="dataSource" class="mons.dbcp.BasicDataSource"destroy-method="close"><!-- 定义数据库连接池数据源bean destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用--><property name="driverClassName" value="${jdbc.driverClassName}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${ername}"/><property name="password" value="${jdbc.password}"/></bean><!—Hibernate的注解配置 --><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="hibernateProperties"><props><prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop><prop key="hibernate.dialect">${hibernate.dialect}</prop><prop key="hibernate.show_sql">${hibernate.show_sql}</prop></props></property><property name="packagesToScan" value="xxx.xxx.xxx.model" /></bean><!-- 配置Hibernate事务管理器 --><bean id="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/></bean><!-- 配置事务异常封装 --><bean id="persistenceExceptionTranslationPostProcessor"class="org.springframework.dao.annotation.PersistenceExceptionTranslationPost Processor"/><!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager --> <tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="add*" propagation="REQUIRED"/><tx:method name="get*" propagation="REQUIRED"/><tx:method name="*" read-only="true"/></tx:attributes></tx:advice><aop:config expose-proxy="true"><!-- 只对业务逻辑层实施事务 --><aop:pointcut id="txPointcut"expression="execution(*xxx.xxx.xxx.service..*.*(..))"/><!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice --><aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/> </aop:config></beans>3、application.properties配置jdbc.driverClassName=org.postgresql.Driverjdbc.url=jdbc:postgresql://ip:5432/数据库名ername=postgresjdbc.password=123hibernate.dialect=org.hibernate.dialect.PostgreSQLDialecthibernate.show_sql=truehibernate.format_sql=false4、spring-mvc.xml配置<?xml version="1.0"encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xmlns:p="/schema/p"xmlns:xsi="/2001/XMLSchema-instance"xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans-3.0.xsd/schema/context/schema/context/spring-context-3.0.xsd/schema/mvc/schema/mvc/spring-mvc-3.0.xsd/schema/tx/schema/tx/spring-tx-4.0.xsd"><!-- 启用spring mvc 注解 --><mvc:annotation-driven><!-- 自动扫描且只扫描@Controller --><context:component-scan base-package="xxx.xxx.xxx "use-default-filters="false"></context:component-scan><!-- 定义JSP文件的位置 --><beanclass="org.springframework.web.servlet.view.InternalResourceView Resolver"><property name="prefix"value="/jsp/"/><property name="suffix"value=".jsp"/></bean><!-- 容器默认的DefaultServletHandler处理所有静态内容与无RequestMapping处理的URL--> <mvc:default-servlet-handler/><!-- 定义无需Controller的url<->view直接映射 --><mvc:view-controller path="/"view-name="login"/></beans>。

Spring中注解配置与xml配置分析

Spring中注解配置与xml配置分析

虽然 2.0 版本发布以来,Spring 陆续提供了十多个注解,但是提供的这些注解只是为了在某些情况下简化 XML 的配置,并非要取代 XML 配置方式。这一点可以从 Spring IoC 容器的初始化类可以看出:ApplicationContext 接口的最常用的实现类是 ClassPathXmlApplicationContext 和 FileSystemXmlApplicationContext,以及面向 Portlet 的 XmlPortletApplicationContext 和面向 web 的 XmlWebApplicationContext,它们都是面向 XML 的。Spring 3.0 新增了另外两个实现类:AnnotationConfigApplicationContext 和 AnnotationConfigWebApplicationContext。从名字便可以看出,它们是为注解而生,直接依赖于注解作为容器配置信息来源的 IoC 容器初始化类。由于 AnnotationConfigWebApplicationContext 是 AnnotationConfigApplicationContext 的 web 版本,其用法与后者相比几乎没有什么差别
也可以单独显式地来启用某个注解处理器,而且可以给处理器添加拦截器:
<be.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="monAnnotationBeanPostProcessor"/>
<mvc:annotation-driven />
当然了也可以使用如下的方式显式地加载:

spring XML优化配置12招

spring XML优化配置12招

spring XML优化配置12招Spring是一个强大的Java应用框架,它广泛地应用于Java应用程序中,为Plain Old Java Objects(POJO)提供企业级服务。

Spring利用依赖注入机制来简化工作,同时提高可测试性。

其配置文件(通常是XML格式)中指定了Spring bean、依赖性以及bean所需的服务。

但是,这些XML配置文件既冗长又不实用。

对于需要定义大量Spring bean的大型项目来说,它们难以阅读和管理。

在本文中,我将向您展示12种用于Spring XML配置的最佳实践。

其中的一些实践与其说是最佳实践,倒不如说是必要实践。

注意,其他因素(如域模型的设置)也可能影响XML的配置,但是本文重点研究XML配置的可读性和可管理性。

1。

避免使用自动绑定(autowiring)功能Spring可以通过bean类的自省自动绑定依赖性,所以不必显式指明bean的属性和构造函数。

Bean属性可以通过属性名称或类型匹配来实现自动绑定。

构造函数通过类型匹配来实现自动绑定。

甚至可以指定自动检测autowiring模式,它可以引导Spring选择一种适当的运行机制。

先来看看下面的一个例子:<bean id="orderService"class="com.lizjason.spring.OrderService"autowire="byName"/>OrderService类的属性名在容器中用于匹配bean实例。

自动绑定可能会节省一些键入工作量并减少混乱。

但是在现实项目中不应该使用这种方式,因为它牺牲了配置的可读性和可维护性。

许多指南和介绍中大肆吹捧自动绑定是Spring的一项极好的特性,而没有提到这一特性所带来的牺牲。

依我来看,这就像Spring中的对象池(object-pooling),更大程度上只是宣传的噱头。

Spring中加载xml配置文件的几种方式

Spring中加载xml配置文件的几种方式

项目中一个需求就是所有的功能都是插件的形式装入系统,这就需要利用Spring去动态加载某一位置下的配置文件,就总结了下Spring中加载xml配置文件的方式, xml是最常见的spring 应用系统配置源。

Spring中的几种容器都支持使用xml装配bean,包括:XmlBeanFactory,ClassPathXmlApplicationContext,FileSystemXmlApplicationContext,XmlWebApplicationContext,.....一: XmlBeanFactory 引用资源1.Resource cr = new ClassPathResource("applicationContext.xml");BeanFactory bf=new XmlBeanFactory(cr);UserDao userDao = (UserDao)bf.getBean("userDao");二: ClassPathXmlApplicationContext 编译路径使用ClassPathXmlApplicationContext对象获取,必须把applicationContext.xml放置到类的加载路径中,也就是Src下面1.ApplicationContext factory=new ClassPathXmlApplicationContext("classpath:appcontext.xml");// src目录下的2.ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao userDao = (UserDao)context.getBean("userDao");3.ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext-oracle.xml","applicationContext.xml"});UserDao userDao = (UserDao)context.getBean("userDao");// src/conf 目录下的4.ApplicationContext factory=new ClassPathXmlApplicationContext("conf/appcontext.xml");5.ApplicationContext factory=new ClassPathXmlApplicationContext("file:G:/Test/src/appcontext.xml");三: FileSystemXmlApplicationContext用文件系统的路径必须把applicationContext.xml放置到工程目录下面,也就是项目路径的下面1.ApplicationContext factory=newFileSystemXmlApplicationContext("src/appcontext.xml");//使用了classpath: 前缀,作为标志, 这样,FileSystemXmlApplicationContext 也能够读入classpath下的相对路径没有classpath的话就是从当前的工作目录2.ApplicationContext factory=newFileSystemXmlApplicationContext("classpath:appcontext.xml");3.ApplicationContext factory=newFileSystemXmlApplicationContext("file:G:/Test/src/appcontext.xml");4.ApplicationContext factory=newFileSystemXmlApplicationContext("G:/Test/src/appcontext.xml");四: XmlWebApplicationContext是专为Web工程定制的。

详解SpringAop实例之xml配置

详解SpringAop实例之xml配置

详解SpringAop实例之xml配置AOP的配置⽅式有2种⽅式:xml配置和AspectJ注解⽅式。

今天我们就来实践⼀下xml配置⽅式。

我采⽤的jdk代理,所以⾸先将接⼝和实现类代码附上package com.tgb.aop;public interface UserManager {public String findUserById(int userId);}package com.tgb.aop;public class UserManagerImpl implements UserManager {public String findUserById(int userId) {System.out.println("---------UserManagerImpl.findUserById()--------");if (userId <= 0) {throw new IllegalArgumentException("该⽤户不存在!");}return "张三";}}单独写⼀个Advice通知类进⾏测试。

这个通知类可以换成安全性检测、⽇志管理等等。

package com.tgb.aop;import ng.JoinPoint;import ng.ProceedingJoinPoint;/*** Advice通知类* 测试after,before,around,throwing,returning Advice.* @author Admin**/public class XMLAdvice {/*** 在核⼼业务执⾏前执⾏,不能阻⽌核⼼业务的调⽤。

* @param joinPoint*/private void doBefore(JoinPoint joinPoint) {System.out.println("-----doBefore().invoke-----");System.out.println(" 此处意在执⾏核⼼业务逻辑前,做⼀些安全性的判断等等");System.out.println(" 可通过joinPoint来获取所需要的内容");System.out.println("-----End of doBefore()------");}/*** ⼿动控制调⽤核⼼业务逻辑,以及调⽤前和调⽤后的处理,** 注意:当核⼼业务抛异常后,⽴即退出,转向After Advice* 执⾏完毕After Advice,再转到Throwing Advice* @param pjp* @return* @throws Throwable*/private Object doAround(ProceedingJoinPoint pjp) throws Throwable {System.out.println("-----doAround().invoke-----");System.out.println(" 此处可以做类似于Before Advice的事情");//调⽤核⼼逻辑Object retVal = pjp.proceed();System.out.println(" 此处可以做类似于After Advice的事情");System.out.println("-----End of doAround()------");return retVal;}/*** 核⼼业务逻辑退出后(包括正常执⾏结束和异常退出),执⾏此Advice* @param joinPoint*/private void doAfter(JoinPoint joinPoint) {System.out.println("-----doAfter().invoke-----");System.out.println(" 此处意在执⾏核⼼业务逻辑之后,做⼀些⽇志记录操作等等");System.out.println(" 可通过joinPoint来获取所需要的内容");System.out.println("-----End of doAfter()------");}/*** 核⼼业务逻辑调⽤正常退出后,不管是否有返回值,正常退出后,均执⾏此Advice* @param joinPoint*/private void doReturn(JoinPoint joinPoint) {System.out.println("-----doReturn().invoke-----");System.out.println(" 此处可以对返回值做进⼀步处理");System.out.println(" 可通过joinPoint来获取所需要的内容");System.out.println("-----End of doReturn()------");}/*** 核⼼业务逻辑调⽤异常退出后,执⾏此Advice,处理错误信息* @param joinPoint* @param ex*/private void doThrowing(JoinPoint joinPoint,Throwable ex) {System.out.println("-----doThrowing().invoke-----");System.out.println(" 错误信息:"+ex.getMessage());System.out.println(" 此处意在执⾏核⼼业务逻辑出错时,捕获异常,并可做⼀些⽇志记录操作等等");System.out.println(" 可通过joinPoint来获取所需要的内容");System.out.println("-----End of doThrowing()------");}}只有Advice还不⾏,还需要在application-config.xml中进⾏配置:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-2.0.xsd /schema/aop /schema/aop/spring-aop-2.0.xsd/schema/tx /schema/tx/spring-tx-2.0.xsd"><bean id="userManager" class="erManagerImpl"/><!--<bean id="aspcejHandler" class="com.tgb.aop.AspceJAdvice"/>--><bean id="xmlHandler" class="com.tgb.aop.XMLAdvice" /><aop:config><aop:aspect id="aspect" ref="xmlHandler"><aop:pointcut id="pointUserMgr" expression="execution(* com.tgb.aop.*.find*(..))"/><aop:before method="doBefore" pointcut-ref="pointUserMgr"/><aop:after method="doAfter" pointcut-ref="pointUserMgr"/><aop:around method="doAround" pointcut-ref="pointUserMgr"/><aop:after-returning method="doReturn" pointcut-ref="pointUserMgr"/><aop:after-throwing method="doThrowing" throwing="ex" pointcut-ref="pointUserMgr"/></aop:aspect></aop:config></beans>编⼀个客户端类进⾏测试⼀下:package com.tgb.aop;import org.springframework.beans.factory.BeanFactory;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Client {public static void main(String[] args) {BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");UserManager userManager = (UserManager)factory.getBean("userManager");//可以查找张三userManager.findUserById(1);System.out.println("=====我==是==分==割==线=====");try {// 查不到数据,会抛异常,异常会被AfterThrowingAdvice捕获userManager.findUserById(0);} catch (IllegalArgumentException e) {}}}结果如图:值得注意的是Around与Before和After的执⾏顺序。

Spring中基于XML的AOP配置详解

Spring中基于XML的AOP配置详解

Spring中基于XML的AOP配置详解⽬录1. 准备⼯作2. 进⾏配置3. 创建测试类AOPTest.java4. 运⾏结果5. ⽬录结构6. 切⼊点表达式写法补充7. 四种通知类型补充8. 通⽤化切⼊点表达式9. Spring的环绕通知1. 准备⼯作1.1 创建⼯程 day03_eesy_03SpringAOP1.2 在配置⽂件pom.xml中添加依赖<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.itheima</groupId><artifactId>day03_eesy_03springAOP</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.4.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.5</version></dependency></dependencies></project>说明: aspect依赖是⽤来声明切⼊点坐标的1.3 编写业务层代码1.创建包 service2.创建业务层接⼝IAccountService.java/*** 账户的业务层接⼝*/public interface IAccountService {/*** 模拟保存账户*/void saveAccount();/*** 模拟更新账户*/void updateAccount(Integer i);/*** 模拟删除账户*/int deleteAccount();}3.创建业务层实现类AccountServiceImpl.java/*** 账户的业务层实现类*/public class AccountServiceImpl implements IAccountService {public void saveAccount() {System.out.println("执⾏了保存");}public void updateAccount(Integer i) {System.out.println("执⾏⼒更新");}public int deleteAccount() {System.out.println("执⾏了删除");return 0;}}4.创建⽇志类该类为⽤于记录⽇志的⼯具类,它⾥⾯提供了公共的代码(通知)Logger.java/*** ⽤于记录⽇志的⼯具类,它⾥⾯提供了公共的代码*/public class Logger {/*** ⽤于打印⽇志,计划让其在切⼊点⽅法执⾏之前执⾏(切⼊点⽅法就是业务层⽅法)*/public void printLog(){System.out.println("Logger类中的printLog⽅法开始记录⽇志了");}}2. 进⾏配置创建配置⽂件 bean.xml先添加包含AOP的约束,后添加配置<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/aop/schema/aop/spring-aop.xsd"><!--配置Spring的IOC,把service对象配置进来--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean><!--Spring中基于XML的AOP配置步骤1.把通知Bean也交给Spring来管理2.使⽤aop:config标签表明开始AOP的配置3.使⽤aop:aspect标签表明配置切⾯id属性: 是给切⾯提供唯⼀标识ref属性: 是指定通知类bean的id4.在aop:aspect标签的内部使⽤对应的标签来配置通知的类型我们现在的⽰例是让Logger类的printLog⽅法在切⼊点⽅法执⾏之前执⾏, 所以是前置通知aop:before : 表⽰配置前置通知method属性: ⽤于指定Logger类中哪个⽅法是前置通知pointcut属性: ⽤于指定切⼊点表达式,该表达式的含义指的是对业务层中哪些⽅法增强切⼊点表达式的写法:关键字: execution(表达式)表达式:访问修饰符返回值包名.包名.包名...类名.⽅法名(参数列表)标准的切⼊点表达式:public void com.itheima.service.impl.AccountServiceImpl.saveAccount()--><!--配置Logger类--><bean id="logger" class="com.itheima.utils.Logger"></bean><!--配置AOP--><aop:config><!--配置切⾯--><aop:aspect id="logAdvice" ref="logger"><!--配置通知的类型,并且建⽴通知⽅法和接⼊点⽅法的关联--><aop:before method="printLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:before> </aop:aspect></aop:config></beans>说明: 切⼊点表达式最好按软件的提⽰写,⾃⼰直接⼿写在测试时容易报错3. 创建测试类AOPTest.java/*** 测试AOP的配置*/public class AOPTest {public static void main(String[] args) {//1.获取容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");//2.获取对象IAccountService accountService = (IAccountService) applicationContext.getBean("accountService"); accountService.saveAccount();}}4. 运⾏结果5. ⽬录结构6. 切⼊点表达式写法补充6.1 介绍<!-- 切⼊点表达式的写法:关键字: execution(表达式)表达式:访问修饰符返回值包名.包名.包名...类名.⽅法名(参数列表)标准的切⼊点表达式:public void com.itheima.service.impl.AccountServiceImpl.saveAccount()访问修饰符可以省略:void com.itheima.service.impl.AccountServiceImpl.saveAccount()返回值可以使⽤通配符,表⽰任意返回值* com.itheima.service.impl.AccountServiceImpl.saveAccount()包名可以使⽤通配符,表⽰任意包,但是⼜⼏级包,就需要写⼏个 *.* *.*.*.*.AccountServiceImpl.saveAccount()包名可以使⽤..表⽰当前包及其⼦包* *..AccountServiceImpl.saveAccount()类名和⽅法名都可以使⽤*来实现通配* *..*.*()参数列表:可以直接写数据类型:基本类型直接写名称 int引⽤类型写包名.类名的⽅式 ng.String可以使⽤通配符表⽰任意类型,但是必须有参数可以是使⽤..表⽰有⽆参数均可,有参数可以是任意类型全通配写法:* *..*.*(..)实际开发中切⼊点表达式的通常写法:切到业务层实现类下的所有的⽅法* com.itheima.service.impl.*.*(..)-->6.2 在bean.xml中表⽰<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/aop/schema/aop/spring-aop.xsd"><!--配置Spring的IOC,把service对象配置进来--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean><!--Spring中基于XML的AOP配置步骤1.把通知Bean也交给Spring来管理2.使⽤aop:config标签表明开始AOP的配置3.使⽤aop:aspect标签表明配置切⾯id属性: 是给切⾯提供唯⼀标识ref属性: 是指定通知类bean的id4.在aop:aspect标签的内部使⽤对应的标签来配置通知的类型我们现在的⽰例是让Logger类的printLog⽅法在切⼊点⽅法执⾏之前执⾏, 所以是前置通知aop:before : 表⽰配置前置通知method属性: ⽤于指定Logger类中哪个⽅法是前置通知pointcut属性: ⽤于指定切⼊点表达式,该表达式的含义指的是对业务层中哪些⽅法增强切⼊点表达式的写法:关键字: execution(表达式)表达式:访问修饰符返回值包名.包名.包名...类名.⽅法名(参数列表)标准的切⼊点表达式:public void com.itheima.service.impl.AccountServiceImpl.saveAccount()访问修饰符可以省略:void com.itheima.service.impl.AccountServiceImpl.saveAccount()返回值可以使⽤通配符,表⽰任意返回值* com.itheima.service.impl.AccountServiceImpl.saveAccount()包名可以使⽤通配符,表⽰任意包,但是⼜⼏级包,就需要写⼏个 *.* *.*.*.*.AccountServiceImpl.saveAccount()包名可以使⽤..表⽰当前包及其⼦包* *..AccountServiceImpl.saveAccount()类名和⽅法名都可以使⽤*来实现通配* *..*.*()参数列表:可以直接写数据类型:基本类型直接写名称 int引⽤类型写包名.类名的⽅式 ng.String可以使⽤通配符表⽰任意类型,但是必须有参数可以是使⽤..表⽰有⽆参数均可,有参数可以是任意类型全通配写法:* *..*.*(..)实际开发中切⼊点表达式的通常写法:切到业务层实现类下的所有的⽅法* com.itheima.service.impl.*.*(..)--><!--配置Logger类--><bean id="logger" class="com.itheima.utils.Logger"></bean><!--配置AOP--><aop:config><!--配置切⾯--><aop:aspect id="logAdvice" ref="logger"><!--配置通知的类型,并且建⽴通知⽅法和接⼊点⽅法的关联--><aop:before method="printLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:before> </aop:aspect></aop:config></beans>6.3 在测试类AOPTest.java中测试/*** 测试AOP的配置*/public class AOPTest {public static void main(String[] args) {//1.获取容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");//2.获取对象IAccountService accountService = (IAccountService) applicationContext.getBean("accountService"); accountService.saveAccount();accountService.updateAccount(1);accountService.deleteAccount();}}6.4 运⾏结果7. 四种通知类型补充7.1 在Logger.java类中添加⽅法/*** ⽤于记录⽇志的⼯具类,它⾥⾯提供了公共的代码*/public class Logger {/*** 前置通知*/public void beforePrintLog(){System.out.println("前置通知:Logger类中的printLog⽅法开始记录⽇志了");}/*** 后置通知*/public void afterReturningPrintLog(){System.out.println("后置通知:Logger类中的printLog⽅法开始记录⽇志了");}/*** 异常通知*/public void afterThrowingPrintLog(){System.out.println("异常通知:Logger类中的printLog⽅法开始记录⽇志了");}/*** 最终通知*/public void afterPrintLog(){System.out.println("最终通知:Logger类中的printLog⽅法开始记录⽇志了");}}7.2 在bean.xml中进⾏配置<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/aop/schema/aop/spring-aop.xsd"><!--配置Spring的IOC,把service对象配置进来--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean><!--配置Logger类--><bean id="logger" class="com.itheima.utils.Logger"></bean><!--配置AOP--><aop:config><!--配置切⾯--><aop:aspect id="logAdvice" ref="logger"><!--配置前置通知: 在切⼊点⽅法执⾏之前执⾏--><aop:before method="beforePrintLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:before><!--配置后通知: 在切⼊点⽅法正常执⾏之后执⾏; 他和异常通知只能执⾏⼀个--><aop:after-returning method="afterReturningPrintLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:after-returning><!--配置异常通知: 在切⼊点⽅法执⾏产⽣异常之后执⾏; 他和后置通知只能执⾏⼀个--><aop:after-throwing method="afterThrowingPrintLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:after-throwing> <!--配置最终通知: ⽆论切⼊点⽅法是否正常执⾏他都会在其后⾯执⾏--><aop:after method="afterPrintLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:after></aop:aspect></aop:config></beans>7.3 在测试类AOPTest.java中运⾏/*** 测试AOP的配置*/public class AOPTest {public static void main(String[] args) {//1.获取容器ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");//2.获取对象IAccountService accountService = (IAccountService) applicationContext.getBean("accountService");accountService.saveAccount();}}7.4 运⾏结果8. 通⽤化切⼊点表达式⽤于解决在bean.xml⽂件中配置通知时多次写切⼊点表达式的问题使⽤ aop:pointcut标签,在bean.xml中进⾏配置8.1 在aop:aspect标签内部使⽤aop:pointcut<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/aop/schema/aop/spring-aop.xsd"><!--配置Spring的IOC,把service对象配置进来--><bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean><!--配置Logger类--><bean id="logger" class="com.itheima.utils.Logger"></bean><!--配置AOP--><aop:config><!--配置切⾯--><aop:aspect id="logAdvice" ref="logger"><!--配置前置通知: 在切⼊点⽅法执⾏之前执⾏--><aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before><!--配置后通知: 在切⼊点⽅法正常执⾏之后执⾏; 他和异常通知只能执⾏⼀个--><aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning><!--配置异常通知: 在切⼊点⽅法执⾏产⽣异常之后执⾏; 他和后置通知只能执⾏⼀个--><aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing><!--配置最终通知: ⽆论切⼊点⽅法是否正常执⾏他都会在其后⾯执⾏--><aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after><!--配置切⼊点表达式 id属性⽤于指定表达式的唯⼀标识, expression属性⽤于指定表达式的内容此标签写在app:aspect标签内部,只能当前切⾯使⽤。

Spring中xml的配置

Spring中xml的配置

Spring中xml的配置(摘抄)出自:1、value元素<value/>元素通过字符串来指定属性或构造器参数的值。

<bean id="myDataSource" detroy-method="close"class="mons.dbcp.BasicDataSource"><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></proerpty><property name="url"><value>jdbc:mysql://localhost:3306/mydb</value></property><property name="username"><vlaue>root</value></property></bean>2、idref元素idref元素用来将容器内其它bean的id传给<constructor-arg/>或<property/>元素,同时提供错误难功能。

<bean id="theTargetBean" class="..."/><bean id="theClientBean" class="..."><property name="targetName"><idref bean="theTargetBean" /></property></bean>等同于:<bean id="theTargetBean" class="..." /><bean id="theClientBean" class="..."><property name="targetName"><value>theTargetBean</value></bean>使用idref标记允许容器在部署时验证所被引用的bean是否存在。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

spring是一个强大的Java应用框架,它广泛地应用于Java应用程序中,为Plain Old Java Objects(POJO)提供企业级服务。

Spring利用依赖注入机制来简化工作,同时提高可测试性。

其配置文件(通常是XML格式)中指定了 Spring bean、依赖性以及bean所需的服务。

但是,这些XML配置文件既冗长又不实用。

对于需要定义大量Spring bean的大型项目来说,它们难以阅读和管理。

在本文中,我将向您展示12种用于Spring XML配置的最佳实践。

其中的一些实践与其说是最佳实践,倒不如说是必要实践。

注意,其他因素(如域模型的设置)也可能影响XML的配置,但是本文重点研究XML配置的可读性和可管理性。

1。

避免使用自动绑定(autowiring)功能Spring 可以通过bean类的自省自动绑定依赖性,所以不必显式指明bean的属性和构造函数。

Bean属性可以通过属性名称或类型匹配来实现自动绑定。

构造函数通过类型匹配来实现自动绑定。

甚至可以指定自动检测autowiring模式,它可以引导Spring选择一种适当的运行机制。

先来看看下面的一个例子:Java代码1.<bean id="orderService"2. class="com.lizjason.spring.OrderService"3. autowire="byName"/>OrderService 类的属性名在容器中用于匹配bean实例。

自动绑定可能会节省一些键入工作量并减少混乱。

但是在现实项目中不应该使用这种方式,因为它牺牲了配置的可读性和可维护性。

许多指南和介绍中大肆吹捧自动绑定是Spring的一项极好的特性,而没有提到这一特性所带来的牺牲。

依我来看,这就像Spring 中的对象池(object-pooling),更大程度上只是宣传的噱头。

对于精简XML 配置文件来说,它是一个好办法,但它实际上增加了复杂性,尤其是在运行包含大量类声明的项目时。

虽然Spring允许混合使用自动绑定和显式绑定,但这会使XML配置更加晦涩难懂。

2.使用命名约定该原则对于Java编码也一样适用。

在项目中使用清晰的、描述性的、一致的命名约定将非常有利于开发人员理解XML配置。

例如,对于bean ID,可以按照Java 类字段名约定来命名它。

OrderServiceDAO实例的bean ID应该命名为orderServiceDAO。

对于大型项目,可以在bean ID前面加上包名作为前缀。

3. 使用简洁形式简洁形式避免了冗长,因为它将属性值和引用从子元素中移入属性中。

例如下面的例子:Java代码1.<bean id="orderService"2. class="com.lizjason.spring.OrderService">3. <property name="companyName">4. <value>lizjason</value>5. </property>6. <constructor-arg>7. <ref bean="orderDAO">8. </constructor-arg>9. </bean>可以使用简洁形式将上述代码重写为:Java代码1.<bean id="orderService"2. class="com.lizjason.spring.OrderService">3.4. <property name="companyName"5. value="lizjason"/>6. <constructor-arg ref="orderDAO"/>7. </bean>简洁形式自1.2版本起就可以使用。

注意,对于<ref local="...">,没有简洁形式。

简洁形式不但可以节约键入工作量,而且可以使XML配置文件更清晰。

当一个配置文件中定义了大量的类时,它可以显著提高可读性。

4. 对于构造函数参数匹配,类型比下标好当构造函数含有一个以上同种类型的参数,或者属性值的标签已经被占用时,Spring允许使用从0开始的下标来避免混淆。

例如:Java代码1.<bean id="billingService"2. class="com.lizjason.spring.BillingService">3. <constructor-arg index="0" value="lizjason"/>4. <constructor-arg index="1" value="100"/>5. </bean>利用type属性来编写会更好一些,如下:Java代码1.<bean id="billingService"2. class="com.lizjason.spring.BillingService">3. <constructor-arg type="ng.String"4. value="lizjason"/>5. <constructor-arg type="int" value="100"/>6. </bean>使用index可以减少一些代码,但是与type属性相比,它更易于出错且难于阅读。

只有在构造函数参数不明确的时候,才应该使用index。

5. 尽可能重用已定义的beanSpring 提供了一种类似于继承的机制来减少配置信息的复制并简化XML配置。

定义一个子类,它就可以从父类那里继承配置信息,而父类实际上成为子类的一个模板。

这就是大型项目中所谓的重用。

只需在父类bean中设置abstract=true,然后在子bean中指定parent引用。

例如:Java代码1.<bean id="abstractService" abstract="true"2. class="com.lizjason.spring.AbstractService">3. <property name="companyName"4. value="lizjason"/>5. </bean>6.7. <bean id="shippingService"8. parent="abstractService"9. class="com.lizjason.spring.ShippingService">10. <property name="shippedBy" value="lizjason"/>11. </bean>ShippingService类从abstractService类继承companyName属性的值——lizjason。

如果一个bean没有指定类或工厂方法,那么这个bean便是抽象的。

6. 在导入时,首选通过ApplicationContext来汇编bean定义像Ant脚本中的导入一样,Spring的import元素对于汇编模块化的bean定义来说是很有用的。

例如:Java代码1.<beans>2. <import resource="billingServices.xml"/>3. <import resource="shippingServices.xml"/>4. <bean id="orderService"5. class="com.lizjason.spring.OrderService"/>6. <beans>然而,相对于使用import在XML配置中进行预汇编,通过ApplicationContext 来配置这些bean则显得更加灵活。

使用 ApplicationContext的话,XML配置也更易于管理。

可以向ApplictionContext构造函数传递一组bean定义,如下:Java代码1.String[] serviceResources =2. {"orderServices.xml",3. "billingServices.xml",4. "shippingServices.xml"};5. ApplicationContext orderServiceContext = new6. ClassPathXmlApplicationContext(serviceResources);7. 使用id作为bean标识符可以指定一个id或名称来作为bean标识符。

虽然使用id不能提高可读性,但是它可以利用XML分析程序来对bean引用进行验证。

如果由于XML IDREF的约束而不能使用某个id,那么可以使用名称来作为bean的标识符。

XML IDREF的约束是:id必须以字母(或者XML规范中定义的标点符号)开头,后面是字母、数字、连字符、下划线、冒号或句点。

实际上,很少会遇到XML IDREF约束问题。

8. 在开发阶段使用依赖性检查(dependency-check)可以在bean定义中为dependency-check属性设置一个非默认值,比如simple、objects或all,以便容器进行依赖性检查。

当需要显式或通过自动绑定设置bean 的全部属性(或某类属性)时,依赖性检查便显得很有用。

Java代码1.<bean id="orderService"2. class="com.lizjason.spring.OrderService"3. dependency-check="objects">4. <property name="companyName"5. value="lizjason"/>6. <constructor-arg ref="orderDAO"/>7. </bean>在这个例子中,容器确保为orderService bean设置的属性不是primitives或collections。

相关文档
最新文档