`
jaesonchen
  • 浏览: 313360 次
  • 来自: ...
社区版块
存档分类
最新评论

applicationContext.xml

 
阅读更多
<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
		http://www.springframework.org/schema/cache 
		http://www.springframework.org/schema/cache/spring-cache.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/security 
		http://www.springframework.org/schema/security/spring-security.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" >

	<!-- 加载资源文件  其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->
    <context:property-placeholder location="classpath:config.properties" />
	
	<!-- 启用组件注解扫描 -->
	<context:component-scan base-package="com.jaeson" />
	
	<!-- 启用AOP注解扫描,@Aspect/@Pointcut/@Before/@After/@Around/@AfterReturning/@AfterThrowing -->
	<aop:aspectj-autoproxy/>
	
	
	<!-- jndi数据源配置 -->
	<!-- 
	<jee:jndi-lookup id="dataSource" name="jndiName" value="${jndiName}" />
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
		<property name="jndiName" value="${jndi.name}"></property>
	</bean>
	<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" /> -->
	<!-- 数据源配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 连接初始值,连接池启动时创建的连接数量的初始值 -->
		<property name="initialSize" value="10" />
		<!-- 连接池的最大值,同一时间可以从池分配的最多连接数量,0时无限制 -->
		<property name="maxActive" value="50" />
		<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="5" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 ,0时无限制-->
		<property name="maxIdle" value="20" />
    </bean>
    	
	<!-- 注册实现了ApplicationContextAware接口的bean组件,Spring将会自动注入ApplicationContext属性。 -->
	<bean class="com.jaeson.springstudy.SpringContextUtil" lazy-init="false" />
	
	
	<!-- 
		依赖注入dependency injection(setter):
		<bean id="exampleBean" class="examples.ExampleBean">
			<property name="beanOne"><ref bean="anotherExampleBean" /></property>
			<property name="beanTwo" ref="yetAnotherBean"/>
			<property name="integerProperty" value="1"/>
			<property name="username" value="root"/>
		</bean>
		<bean id="anotherExampleBean" class="examples.AnotherBean" />
		<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
		
		构造器注入constructor injection: the container can use type matching with simple types if you explicitly specify 
			the type of the constructor argument using the type attribute. 
		<bean id="foo" class="x.y.Foo">
	        <constructor-arg ref="bar"/>
	        <constructor-arg ref="baz"/>
	        <constructor-arg type="int" value="7500000"/>
	        <constructor-arg type="java.lang.String" value="42"/>
		</bean>
	    <bean id="bar" class="x.y.Bar"/>
	    <bean id="baz" class="x.y.Baz"/>
		
		代理注入in the parent context:
		<bean id="accountService" class="com.foo.SimpleAccountService" />
		in the child context(bean name is the same as the parent bean):
		<bean id="accountService"
    		class="org.springframework.aop.framework.ProxyFactoryBean">
    		<property name="target">
        		<ref parent="accountService"/>
    		</property>
		</bean>
		
		集合注入Collections injection:
		<bean id="moreComplexObject" class="example.ComplexObject">
			<property name="adminEmails">
  				<props>
      				<prop key="administrator">administrator@example.org</prop>
  				</props>
			</property>

			<property name="someList">
  				<list>
      				<value>a list element followed by a reference</value>
      				<ref bean="myDataSource" />
  				</list>
			</property>
			<property name="someMap">
  				<map>
					<entry key="an entry" value="just some string"/>
					<entry key ="a ref" value-ref="myDataSource"/>
				</map>
			</property>
			<property name="someSet">
				<set>
					<value>just some string</value>
					<ref bean="myDataSource" />
				</set>
			</property>
		</bean>
		
		泛型集合strongly-typed collection:
		private Map<String, Float> accounts;
		<bean id="foo" class="x.y.Foo">
	        <property name="accounts">
	            <map>
	                <entry key="two" value="2.75"/>
	                <entry key="six" value="3.99"/>
	            </map>
	        </property>
    	</bean>
		
		null和空串注入Null and empty string values:
		<bean class="ExampleBean">
			<property name="email" value=""/>
			<property name="address"><null/></property>
		</bean>
		
		
		延迟创建lazy-init:By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process.
		A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
		<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
		You can also control lazy-initialization at the container level by using the default-lazy-init attribute on the <beans/> element.
		<beans default-lazy-init="true" />  //no beans will be pre-instantiated
		
		
		自动注入模式Autowiring modes:
		byName: Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired.
 		byType: Allows a property to be autowired if exactly one bean of the property type exists in the container. 
 				If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. 
 				If there are no matching beans, nothing happens; the property is not set.
 		constructor: Analogous(类似) to byType, but applies to constructor arguments. 
 				If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
		With byType or constructor autowiring mode, you can wire arrays and typed-collections. In such cases all autowire candidates 
			within the container that match the expected type are provided to satisfy(满足) the dependency. You can autowire strongly-typed Maps 
			if the expected key type is String. An autowired Maps values will consist of all bean instances that match the expected type, 
			and the Maps keys will contain the corresponding bean names.
		
		ApplicationContextAware: When an ApplicationContext creates a class that implements the org.springframework.context.ApplicationContextAware 
			interface, the class is provided with a reference to that ApplicationContext.
		
		
		单例和原型Bean scopes:
		singleton scope is the default.
		prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. 
			Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, 
			and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.
			Thus, although initialization lifecycle callback methods are called on all objects regardless of(不论) scope, in the case of prototypes, 
			configured destruction lifecycle callbacks are not called.  
		<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>
		
		
		生命周期回调Lifecycle callbacks: To interact with the container's management of the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces.
			It is recommended that you do not use the interface. Alternatively, use the @PostConstruct and @PreDestroy annotation or specify a POJO method.
		<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
		<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/> -->

		
		<!-- 
		注解配置Annotation-based container configuration: Annotation injection is performed before XML injection, thus the latter configuration 
		will override the former for properties wired through both approaches. The implicitly registered post-processors include 
		AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, RequiredAnnotationBeanPostProcessor
		<context:annotation-config/> only looks for annotations on beans in the same application context in which it is defined.
		
		
		@Required: The @Required annotation applies to bean property setter methods.
			This annotation simply indicates that the affected bean property must be populated at configuration time, 
			through an explicit property value in a bean definition or through autowiring. The container throws an exception 
			if the affected bean property has not been populated.
		@Required
  		public void setMovieFinder(MovieFinder movieFinder) {}
		
		
		@Autowired: autowiring by type. @Autowired applies to fields, constructors, setter and multi-argument methods, 
					allowing for narrowing through qualifier annotations at the parameter level.
		@Autowired
		private MovieCatalog movieCatalogs;
		@Autowired
  		private MovieCatalog[] movieCatalogs;	//provide all beans of a particular type from the ApplicationContext that expects an array of that type
  		@Autowired
		public MovieRecommender(CustomerDao customerDao) {}
  		@Autowired
		public void setMovieFinder(MovieFinder movieFinder) {}
		@Autowired
		public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {}
		@Autowired
  		public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {}
  		@Autowired
    	public void prepare(MovieCatalog movieCatalog, CustomerDao customerDao) {}
    	By default, the autowiring fails whenever zero candidate beans are available. This behavior can be changed as demonstrated below.
    	@Autowired(required=false)
   		public void setMovieFinder(MovieFinder movieFinder) {}
   		You can also use @Autowired for interfaces that are well-known resolvable dependencies: BeanFactory, ApplicationContext. 
   			They are automatically resolved, with no special setup necessary.
   		@Autowired
		private ApplicationContext context;
   		

		@Qualifier: autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. 
			With Spring's @Qualifier annotation. You can associate qualifier values with specific arguments.
		@Autowired
		@Qualifier("main")
    	private MovieCatalog movieCatalog;
		@Autowired
		@Qualifier("movies")
		public void setMovie(Set<MovieCatalog> movie) {}	//all matching beans according to the declared qualifiers("movies") are injected as a collection
		@Autowired
		public void prepare(@Qualifier("main")MovieCatalog movieCatalog, CustomerDao customerDao) {}
        @Autowired
		public Movie(@Qualifier("movieDao") CustomerDao customerDao) {}
		
		
		@Resource: JSR-250 @Resource takes a name attribute, and by default Spring interprets(解释) that value as the bean name to be injected.
			If you intend to express annotation-driven injection by name, user JSR-250 @Resource annotation, 
			which is semantically(语义上 ) defined to identify a specific target component by its unique name.
			If no name is specified explicitly, the default name is derived from the field name or setter method. 
			In case of a field, it takes the field name; in case of a setter method, it takes the bean property name. 
			@Resource is supported only for fields and bean property setter methods with a single argument.
		@Resource(name="movie")
		private Movie movie;
		@Resource
		public void setMovieFinder(MovieFinder movieFinder) {}
		
		
		@PostConstruct and @PreDestroy:
		@PostConstruct
		public void populateMovieCache() {}
		@PreDestroy
  		public void clearMovieCache() {}
  		
		
		@Component is a generic stereotype for any Spring-managed component. 
		@Repository, @Service, and @Controller are specializations of @Component for more specific use cases, 
			for example, in the persistence, service, and presentation layers, respectively(各自). 
		@Repository is already supported as a marker for automatic exception translation in your persistence layer.	
		Spring can automatically detect stereotyped classes and register corresponding BeanDefinitions with the ApplicationContext. 
		Need to include the <context:component-scan base-package="org.example"/> in XML.
		<context:component-scan> implicitly enables the functionality of <context:annotation-config>. 
		There is usually no need to include the <context:annotation-config> element when using <context:component-scan>. 
		By default, any Spring stereotype annotation ( @Component, @Repository, @Service, and @Controller) that contains a name value will 
		thereby(因此) provide that name to the corresponding bean definition. If such an annotation contains no name value or for any other detected 
		component, the default bean name generator returns the uncapitalized non-qualified class name. 
		
		@Service
		public class SimpleMovieService {}	//beanName = simpleMovieService
		
		
		使用扫描过滤Using filters to customize scanning:
		<context:component-scan base-package="org.example">
	        <context:include-filter type="regex"
	                expression=".*Stub.*Repository"/>
	        <context:exclude-filter type="annotation"
	                expression="org.springframework.stereotype.Repository"/>
    	</context:component-scan>
    
		
		JSR-330标准注解Dependency Injection with @Inject and @Named: it is possible to use @Inject at the class-level, field-level, method-level and constructor-argument level. 
		Spring 4.0 offers support for JSR-330 standard annotations (Dependency Injection). 
		<dependency>
		    <groupId>javax.inject</groupId>
		    <artifactId>javax.inject</artifactId>
		    <version>1</version>
		</dependency>
		@Inject
  		public void setMovieFinder(@Named("movie") MovieFinder movieFinder) {}
		@Named("movieListener")		//a standard equivalent to the @Component annotation
		public class SimpleMovieLister {}
		
		Spring annotations and JSR-330 standard annotations: @Autowired=@Inject, @Component=@Named, @Qualifier=@Named, ObjectFactory=Provider.
 		The JSR-330 default scope is like Spring’s prototype. However, in order to keep it consistent(一致) with Spring’s general defaults, 
 		a JSR-330 bean declared in the Spring container is a singleton by default. In order to use a scope other than singleton, 
 		you should use Spring’s @Scope annotation. javax.inject also provides a @Scope annotation.  -->
 		
 		
		<!-- 
		基于java代码的配置Java-based container configuration: Spring's new Java-configuration support are @Configuration-annotated classes and @Bean-annotated methods.
		@Bean: is a method-level annotation and a direct analog(模拟) of the XML <bean/> element.
			The @Bean annotation is used to indicate that a method instantiates, 
			configures and initializes a new object to be managed by the Spring IoC container. 
		@Configuration: @Configuration is a class-level annotation indicating that an object is a source of bean definitions. 
			@Configuration classes declare beans via public @Bean annotated methods.
			Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. 
			Using <context:component-scan/> to pick up @Configuration classes.
		@Configuration
		public class AppConfig {
  			@Bean
  			@Scope("prototype")
  			public MyService myService() {
      			return new MyServiceImpl();
  			}
  			@Bean
    		public TransferService transferService(AccountRepository accountRepository) {
        		return new TransferServiceImpl(accountRepository);
    		}	
		}
		The AppConfig class above would be equivalent to the following Spring <beans/> XML: 
		<bean id="myService" class="com.acme.services.MyServiceImpl"/>
		<bean id="accountRepository" class="com.acme.dao.AccountRepository"/>
		<bean id="transferService" class="com.acme.services.TransferServiceImpl">
			constructor-arg ref="accountRepository"/>
		</bean> -->
		
		
		<!-- 
		web.xml配置 ApplicationContext instantiation for web applications:
		<context-param>
		    <param-name>contextConfigLocation</param-name>
		    <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>
		</context-param>
		<listener>
		    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
		</listener> -->
		
		
		<!-- 
		Spring AOP
		•the execution of any public method:
			execution(public * *(..))
		•the execution of any method with a name beginning with "set":
			execution(* set*(..))
		•the execution of any method defined by the AccountService interface:
			execution(* com.xyz.service.AccountService.*(..))
		•the execution of any method defined in the service package:
			execution(* com.xyz.service.*.*(..))
		•the execution of any method defined in the service package or a sub-package:
			execution(* com.xyz.service..*.*(..))
		•any join point (method execution only in Spring AOP) within the service package: 
			within(com.xyz.service.*)
		•any join point (method execution only in Spring AOP) within the service package or a sub-package: 
			within(com.xyz.service..*)
		

		Spring AOP is proxy-based.
		Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies. This enables any interface (or set of interfaces) to be proxied.
		Spring AOP can also use CGLIB proxies. This is necessary to proxy classes rather than interfaces. CGLIB is used by default if a business object
		does not implement an interface. As it is good practice to program to interfaces rather than classes; business classes normally will 
		implement one or more business interfaces. It is possible to force the use of CGLIB, in those cases where you need to advise a method that 
		is not declared on an interface, or where you need to pass a proxied object to a method as a concrete type.
		

		To enable @AspectJ support with XML based configuration use the aop:aspectj-autoproxy element:
		<aop:aspectj-autoproxy/>
		
		<aop:config>
			<aop:aspect id="myAspect" ref="adviceBean">
				<aop:pointcut id="businessService"
	        		expression="execution(* com.xyz.myapp.service.*.*(..))" />
	        	<aop:before pointcut-ref="businessService" method="doAccessCheck"/>
	        	<aop:around 
	        		pointcut-ref="businessService"
        			method="doBasicProfiling" />
	        </aop:aspect>
		</aop:config>
		
		
		Proxying mechanisms: Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. 
			(JDK dynamic proxies are preferred whenever you have a choice). If the target object to be proxied implements at least one interface 
			then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied. If the target object 
			does not implement any interfaces then a CGLIB proxy will be created. If you want to force the use of CGLIB proxying you can do so. 
			However, there are some issues to consider: final methods cannot be advised, as they cannot be overridden. 
			
			To force the use of CGLIB proxies set the value of the proxy-target-class attribute of the <aop:config> element to true:
			<aop:config proxy-target-class="true" />
			To force CGLIB proxying when using the @AspectJ autoproxy support, set the 'proxy-target-class' attribute element to true:
			<aop:aspectj-autoproxy proxy-target-class="true"/>
			<tx:annotation-driven proxy-target-class="true"/>
			
		The key thing to understand is that the client code has a reference to the proxy. This means that method calls on that object reference 
		will be calls on the proxy, and as such the proxy will be able to delegate to all of the interceptors (advice) that are relevant to 
		that particular method call. However, once the call has finally reached the target object, any method calls that it may make on itself, 
		such as this.method(), are going to be invoked against the this reference, and not the proxy. This has important implications. 
		It means that self-invocation is not going to result in the advice associated with a method invocation getting a chance to execute.
		
		The best approach is to refactor your code such that the self-invocation does not happen. 
		public class SimplePojo implements Pojo {
		    public void foo() {
		        // this works, but... ugly!
		        ((Pojo) AopContext.currentProxy()).bar();
		    }
		    public void bar() {
		        // some logic...
		    }
		}
		
		
		Proxying:
		<bean id="personTarget" class="com.mycompany.PersonImpl" />
		<bean id="myAdvisor" class="com.mycompany.MyAdvisor" />
		<bean id="debugInterceptor" class="org.springframework.aop.interceptor.DebugInterceptor" />
		<bean id="person" class="org.springframework.aop.framework.ProxyFactoryBean">
    		<property name="proxyInterfaces" value="com.mycompany.Person"/>
			<property name="target" ref="personTarget"/>
    		<property name="interceptorNames">
		        <list>
		            <value>myAdvisor</value>
		            <value>debugInterceptor</value>
		        </list>
		    </property>
		</bean>
		
			
		Spring Framework does not support propagation of transaction contexts across remote calls.
		
		In its default configuration, the Spring Framework's transaction infrastructure code only marks a transaction for 
			rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. 
			(Errors will also - by default - result in a rollback). Checked exceptions that are thrown from a transactional method do not 
			result in rollback in the default configuration.
		
		指定回滚规则indicate rollback rules
		When the Spring Framework's transaction infrastructure catches an exception and is consults configured rollback rules to determine 
			whether to mark the transaction for rollback, the strongest matching rule wins.
		<tx:method name="get*"		rollback-for="NoProductInStockException"/>
		<tx:method name="update*"	no-rollback-for="InstrumentNotFoundException"/>
		<tx:method name="*" 		rollback-for="Throwable"	no-rollback-for="InstrumentNotFoundException"/>
		
		硬编码回滚Programmatic rollback tightly couples your code to the Spring Framework's transaction infrastructure.
		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		
		缺省的设置The default <tx:advice/> settings:
		•Propagation setting is REQUIRED.
		•Isolation level is DEFAULT.
		•Transaction is read/write.
		•Transaction timeout defaults to the default timeout of the underlying transaction system, or none if timeouts are not supported.
		•Any RuntimeException and Error triggers rollback, and any checked Exception does not. -->
		
		
		<!--  
		注解事务@Transactional
		enable the configuration of transactional behavior based on annotations:
		<tx:annotation-driven transaction-manager="transactionManager"/>
		
		You can place the @Transactional annotation before an interface definition, a method on an interface, a class definition, or a public method on a class. 
			you should apply the @Transactional annotation only to methods with public visibility.
			@Transactional annotation on the method in the same class takes precedence(优先) over the transactional settings defined at the class level.
		Spring recommends that you only annotate concrete classes (and methods of concrete classes) with the @Transactional annotation, 
			as opposed to(而不是) annotating interfaces.You certainly can place the @Transactional annotation on an interface (or an interface method), 
			but this works only as you would expect it to if you are using interface-based proxies. The fact that Java annotations are not 
			inherited from interfaces means that if you are using class-based proxies (proxy-target-class="true") 
			or the weaving-based aspect (mode="aspectj"), then the transaction settings are not recognized 
			by the proxying and weaving infrastructure, and the object will not be wrapped in a transactional proxy, which would be decidedly bad.
			
		调用同类方法(this.method())不会触发事务拦截In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. 
			This means that self-invocation, in effect, a method within the target object calling another method of the target object, 
			will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.
			
		代理类型设置The proxy-target-class attribute controls what type of transactional proxies are created for classes annotated 
			with the @Transactional annotation. If proxy-target-class is set to true, class-based proxies are created. 
			If proxy-target-class is false or if the attribute is omitted, standard JDK interface-based proxies are created.
		
		缺省的设置@Transactional settings:
		•Propagation setting is PROPAGATION_REQUIRED.
		•Isolation level is ISOLATION_DEFAULT.
		•Transaction is read/write.
		•Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported.
		•Any RuntimeException and Error triggers rollback, and any checked Exception does not.

		异常转换@Repository
		The best way to guarantee(确保) that your Data Access Objects (DAOs) or repositories provide exception translation is to use the @Repository annotation. 
		@Repository
		public class JdbcMovieFinder implements MovieFinder {}
		
		最佳实践JdbcTemplate best practices
			Instances of the JdbcTemplate class are threadsafe once configured. This is important because it means that you can 
			configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs (or repositories).
			A common practice when using the JdbcTemplate class is to configure a DataSource in your Spring configuration file, 
			and then dependency-inject that shared DataSource bean into your DAO classes; the JdbcTemplate is created in the setter for the DataSource.
		@Repository
		public class JdbcMovieFinder implements MovieFinder {
			private JdbcTemplate jdbcTemplate;
			@Autowired
			public void init(DataSource dataSource) {
				this.jdbcTemplate = new JdbcTemplate(dataSource);
			}
			// ...
		}
		
		sql异常转换SQLExceptionTranslator is an interface to be implemented by classes that can translate between SQLExceptions 
			and Spring's own org.springframework.dao.DataAccessException, which is agnostic(不可知) in regard to data access strategy.  -->


	<!-- 
		@Autowired  自动注入 bean:@Autowired默认按照类型匹配byType的方式进行注入 ,@Autowired 注解可以用于 Setter 方法、构造函数、字段,甚至普通方法,前提是方法必须有至少一个参数。
		@Autowired 标注作用于普通方法时,会产生一个副作用,就是在容器初始化该 Bean 实例的时候就会调用该方法。
		@Autowired 如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,
		那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。
		@Autowired注解须有且仅有一个与之匹配的Bean,当找不到匹配的 Bean 或者存在多个匹配的Bean时,Spring 容器将抛出 异常 。
		可以给 @Autowired 标注增加一个 required=false 属性,以改变这个行为。
		Spring 允许我们通过 @Qualifier 注释增加一个候选值指定注入 Bean 的名称。推荐放置在参数前面。
		@Autowired 和 @Qualifier 结合使用时,自动注入的策略就从 byType 转变成 byName 了。 -->
		
	<!-- 
		JSR-250 中的@Resource 的作用相当于 @Autowired,只不过 @Autowired 默认按 byType 自动注入,@Resource 默认按 byName 自动注入。
		@Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将 @Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。
		所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。
		如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略,默认值就是字段或者属性的名字。 
		推荐使用@Resource注解,而不要使用@Autowired注解, 因为@Autowired注解是Spring提供的,而@Resource注解是J2EE提供的 。 -->
		
	<!-- 
		@Required 进行 Bean 的依赖检查:
		依赖检查的作用是,判断给定 Bean 的相应 Setter 方法是否都在实例化的时候被调用了。而不是判断字段是否已经存在值了。
		Spring 进行依赖检查时,只会判断属性是否使用了 Setter 注入。如果某个属性没有使用 Setter 注入,即使是通过构造函数已经为该属性注入了值,
		Spring 仍然认为它没有执行注入,从而抛出异常。另外,Spring 只管是否通过 Setter 执行了注入,而对注入的值却没有任何要求,
		即使注入的 null,Spring 也认为是执行了依赖注入。 -->
		
	<!-- 
		JSR-250 规范定义了两个用于指定生命周期方法的注解:@PostConstruct 和 @PreDestroy。
		这两个注解使用非常简单,只需分别将他们标注于初始化之后执行的回调方法或者销毁之前执行的回调方法上。  -->	 
		
	<!-- 
		Bean 后处理器隐式注册:post-processors 包括了 AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,
		PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor。
		<context:annotation-config />
		Bean 后处理器@Autowired 显式注册:
    	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
		Bean 后处理器@Resource、@PostConstruct、@PreDestroy 显式注册:
		<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/> -->
	
	<!-- 
		启用Bean 的自动扫描功能:所有标注了@Repository、@Service、@Controller 和 @Component 的类都将被注册为 Spring Bean。 
		Spring会自动创建相应的 BeanDefinition 对象,并注册到 ApplicationContext 中。
		@Component是所有受Spring管理组件的通用形式,仅仅表示一个组件 (Bean),可以作用在任何层次。 而@Repository、@Service和 @Controller则是@Component的细化,
		用来表示更具体的用例(分别对应了持久化层、业务层和表现层)。
		
		@Repository 只能标注在 DAO 类上,这是因为该注解的作用不只是将类识别为Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型。
		Spring本身提供了一个丰富的并且是与具体的数据访问技术无关的数据访问异常结构,用于封装不同的持久层框架抛出的异常,使得异常独立于底层的框架。
		
		在使用组件扫描<context:component-scan/>时,AutowiredAnnotationBeanPostProcessor 和CommonAnnotationBeanPostProcessor会隐式地被包括进来。
		无需再配置<context:annotation-config> -->
		
		
	<!-- 
		配置注解事务: @Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上。
		Spring团队的建议在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。
		@Transactional 标注在 Class 上面, 那么将会对这个 Class 里面所有的 public 方法都包装事务方法。
		在方法上的@Transactional注解会覆盖掉类上的@Transactional。 
		@Transactional 的事务开启 ,或者是基于接口的 或者是基于类的代理被创建。所以在同一个类中一个非事务方法调用另一个有事务的方法,事务是不会起作用的,
		此时要想让事务起作用必须在非事务方法中取得代理对象,使用代理对象调用事务方法,而不能直接用this.method()调用。((Pojo) AopContext.currentProxy()).method().
		@Transactional有几个属性是可以配置的  readOnly, isolation, propagation, rollbackFor, noRollbackFor。
		readOnly标识当与propagation机制同时使用之时,则会出现只读设置被覆盖的情况。
		
		Spring的AOP事务管理默认是针对unchecked exception回滚(运行期异常,RuntimeException,Error也会回滚)。如果异常被try catch了且没有再throw出来,事务就不回滚了。	
		RunTimeException是Exception的子类。MyException extends Exception / RunTimeException extends Exception。
		@Transactional缺省值为:rollbackFor = {RunTimeException} / noRollbackFor = {Exception - RunTimeException}。
		当Spring捕获到异常时,会先查找rollbackFor和noRollbackFor集合,根据配置的结果设置是否回滚标志;如果找不到匹配的结果则使用Spring的默认设置(回滚RuntimeException)。
		当同时匹配到rollbackFor和noRollbackFor中的结果时,取最严格的规则,比如Exception和MyException同时匹配时,取MyException作为匹配结果。
		所有例外回滚:@Transactional(rollbackFor=Exception.class)
		unchecked例外不回滚,其他例外回滚:@Transactional(rollbackFor=Exception.class, noRollbackFor=RuntimeException.class)
			
		propagation常用属性:
		Propagation.REQUIRED: 业务方法需要在一个容器里运行。如果方法运行时,已经处在一个事务中,那么加入到这个事务,否则自己新建一个新的事务。
		Propagation.SUPPORTS: 该方法在某个事务范围内被调用,则方法成为该事务的一部分。如果方法在该事务范围外被调用,该方法就在没有事务的环境下执行。
		Propagation.NOT_SUPPORTED: 声明方法不需要事务。如果方法没有关联到一个事务,容器不会为他开启事务,如果方法在一个事务中被调用,该事务会被挂起,调用结束后,原先的事务会恢复执行。
		Propagation.REQUIRESNEW: 不管是否存在事务,该方法总汇为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务挂起,新的事务被创建。 
		 
		@Transactional(readOnly=true) 只读,不能更新,删除。 -->
		
	<!-- 
		基于JDK动态代理 ,可以将@Transactional放置在接口和具体类上。
		基于CGLIB类代理,只能将@Transactional放置在具体类上。
		在接口上标注@Transactional注解,会留下这样的隐患:因为注解不能被继承,所以业务接口中标注的@Transactional注解不会被业务实现类继承。
		所以可能会出现不启动事务的情况。所以,Spring建议我们将@Transaction注解在实现类上。
		默认基于jdk代理,配置基于CGLIB类代理: 
		<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> -->	
	
</beans>

 

 

分享到:
评论

相关推荐

    applicationContext.xml 详细配置

    ApplicationContext.xml 配置详解 ApplicationContext.xml 是 Spring 框架中用于配置应用程序的核心配置文件。通过该文件,可以定义 Bean、数据源、Session 工厂、 Hibernate 配置等相关信息,从而实现应用程序的...

    applicationContext.xml详解

    ApplicationContext.xml详解 ApplicationContext.xml是Spring框架中的核心配置文件,它是Spring的IOC(Inverse of Control,控制反转)容器的核心组件。该文件用于定义和配置Spring应用程序中的各种Bean,对于...

    struts.xml和applicationContext.xml、web.xml的配置

    在Java Web开发中,`struts.xml`, `applicationContext.xml` 和 `web.xml` 是三个至关重要的配置文件,它们各自负责不同的职责,并协同工作来构建一个完整的应用框架。以下是关于这三个配置文件的详细说明。 首先,...

    applicationContext.xml等文件.rar

    在IT行业中,尤其是在Java Web开发领域,`applicationContext.xml`、`db.properties`、`log4j.properties`以及`spring-mvc.xml`等文件是非常关键的配置文件,它们各自负责不同的功能,对于一个完整的应用程序来说不...

    spring3.0 + Quartz1.52 + applicationContext.xml

    这个压缩包“spring3.0 + Quartz1.52 + applicationContext.xml”显然是一个关于如何在Spring 3.0环境中集成Quartz 1.52版本的示例或教程资源。 首先,`applicationContext.xml`是Spring框架的核心配置文件,它定义...

    SSH框架applicationContext.xml头部文件

    ### SSH框架applicationContext.xml头部文件知识点解析 #### 一、SSH框架简介 SSH框架是Struts+Spring+Hibernate三个开源框架的组合,是中国开发者对这三个框架整合应用的一种简称。其中Struts负责MVC(Model-View-...

    Spring 2.5-applicationContext.xml提示信息的配置

    在Spring框架中,`applicationContext.xml`是应用上下文的核心配置文件,用于定义bean的创建、依赖关系以及各种服务的配置。这篇博文“Spring 2.5 - applicationContext.xml提示信息的配置”主要探讨了如何在Spring ...

    ApplicationContext.xml

    《ApplicationContext.xml——Spring框架的核心配置文件详解》 在Java开发领域,Spring框架是不可或缺的一部分,它以其强大的依赖注入(Dependency Injection,简称DI)和面向切面编程(Aspect-Oriented ...

    SSH中applicationContext.xml如何配制事务

    在SSH的applicationContext.xml 中如何配制配制事务

    applicationContext.xml用法

    ### Spring的applicationContext.xml文件详解 #### 一、引言 在Java开发领域,Spring框架因其强大的功能和灵活的设计而受到广泛欢迎。其中,`applicationContext.xml`是Spring框架的核心配置文件之一,它用于管理...

    spring+jpa的applicationContext.xml配置

    spring+jpa的applicationContext.xml配置

    ssm框架基础配置文件web.xml模板springmvc.xml模板applicationContext.xml模板拿来即用

    3. **applicationContext.xml**:这是Spring的上下文配置文件,主要管理服务层(Service)和数据访问层(DAO)的Bean。包括Bean的定义、依赖注入(DI)、事务管理、AOP(面向切面编程)等配置。 - Bean定义:使用`...

    ssm applicationContext.xml,SpringMVC,web设置

    这是一些配置文件,可以作为参考,个人感觉很方便的学习方法

Global site tag (gtag.js) - Google Analytics