@autoconfigureafter注解configure是什么意思思

spring-boot配置外部静态资源的方法
时间: 14:29:54
&&&& 阅读:2617
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&
import java.io.F
import javax.servlet.S
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureA
import org.springframework.boot.autoconfigure.condition.ConditionalOnC
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingB
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebA
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoC
import org.springframework.boot.autoconfigure.web.WebMvcAutoC
import org.springframework.context.annotation.C
import org.springframework.core.O
import org.springframework.core.annotation.O
import org.springframework.web.servlet.DispatcherS
import org.springframework.web.servlet.config.annotation.ResourceHandlerR
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationS
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerA
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class})
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@Order(Ordered.HIGHEST_PRECEDENCE )
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class StaticResourceConfiguration extends WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
File directory = new File("");
String path2=directory.getAbsolutePath();
StringBuilder builder = new StringBuilder();
builder.append("file:").append(path2).append("/m/");
//registry.addResourceHandler("/**").addResourceLocations( builder.toString() );
//String myExternalFilePath = "file:///C:/Temp/whatever/m/";
( builder.toString() );
registry.addResourceHandler("/m/**").addResourceLocations("file:m/");
//registry.addResourceHandler("/m/**").addResourceLocations(builder.toString());
super.addResourceHandlers(registry);
&标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&原文:/feika/p/4543754.html
&&国之画&&&& &&&&&&
&& &&&&&&&&&&&&&&
鲁ICP备号-4
打开技术之扣,分享程序人生!AutoConfigureAfter (Spring Boot Docs 1.4.1.RELEASE API)
JavaScript is disabled on your browser.
Annotation Type AutoConfigureAfter
public @interface AutoConfigureAfter
Hint for that an
should be applied
after other specified auto-configuration classes.
Phillip Webb
Optional Element Summary
Optional Elements&
Modifier and Type
Optional Element and Description
The names of the auto-configure classes that should have already been applied.
The auto-configure classes that should have already been applied.
Element Detail
public abstract&&?&[]&value
The auto-configure classes that should have already been applied.
the classes
public abstract&[]&name
The names of the auto-configure classes that should have already been applied.
the class names
Copyright © 2016 . All rights reserved.14068人阅读
Spring(33)
看本文之前,请确保你已经在SpringBoot中集成MyBatis,并能正常使用。
如果没有,那么请先移步
做了解后,再按本文步骤操作。
使用MyBatis在我们通过xml集中配置SQL,并通过创建接口Mapper文件来完成持久化DAO层(mybatis内部使用的是动态代理,所以我们不需要自己编写实现类)。
然而在实际开发中,单表操作非常多,如果你也想像JPA、JDBC那样做一个所谓的BaseDao。那么可以实现一个通用Mapper来达到目的。现在有现成的通用Mapper插件,我们无需重新创造轮子(代码是开源的,你也可以自己在其基础上修改)。
通用Mapper插件网址:
下面是使用方法(本文直接将分页插件PageHelper也集成了):
一、添加或修改pom依赖
&org.mybatis&
&org.mybatis&
&mybatis-spring&
&com.github.pagehelper&
&pagehelper&
&tk.mybatis&
这里说一下,文章开始指定的那篇文章中直接依赖的mybatis的starter。因为本文在集成通用Mapper的时候直接使用出现了错误,所以将mybatis的starter中的Java类(它本身只有2个Java类,非常简单)拷贝到工程中,注释掉了头部的//@ConditionalOnBean(DataSource.class),你不用去找那2个类的源码了,下面会粘贴出来。
二、将下面4个Java类加入到工程中
MybatisAutoConfiguration.java
MyBatisMapperScannerConfig.java
MybatisProperties.java
MyMapper.java
添加到 org.springboot.sample.config.mybatis 中(包名根据自己工程修改)
最有一个MyMapper.java要特别注意,不要把MyMapper放到同其他Mapper一起,该类不能被当做普通Mapper一样被扫描,否则会出错。
package org.springboot.sample.config.mybatis
import java.util.Properties
import javax.annotation.PostConstruct
import javax.sql.DataSource
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.ibatis.plugin.Interceptor
import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.SqlSessionFactoryBean
import org.mybatis.spring.SqlSessionTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.AutoConfigureAfter
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.io.DefaultResourceLoader
import org.springframework.core.io.Resource
import org.springframework.core.io.ResourceLoader
import org.springframework.util.Assert
import org.springframework.util.StringUtils
import com.github.pagehelper.PageHelper
@Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
//@ConditionalOnBean(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration {
private static Log log = LogFactory.getLog(MybatisAutoConfiguration.class)
@Autowired
private MybatisProperties properties
@Autowired(required = false)
private Interceptor[] interceptors
@Autowired
private ResourceLoader resourceLoader = new DefaultResourceLoader()
@PostConstruct
public void checkConfigFileExists() {
if (this.properties.isCheckConfigLocation()) {
Resource resource = this.resourceLoader
.getResource(this.properties.getConfig())
Assert.state(resource.exists(),
"Cannot find config location: " + resource
+ " (please add config file or check your Mybatis "
+ "configuration)")
@Bean(name = "sqlSessionFactory")
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean()
factory.setDataSource(dataSource)
if (StringUtils.hasText(this.properties.getConfig())) {
factory.setConfigLocation(
this.resourceLoader.getResource(this.properties.getConfig()))
if (this.interceptors != null && this.interceptors.length & 0) {
factory.setPlugins(this.interceptors)
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage())
factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage())
factory.setMapperLocations(this.properties.getMapperLocations())
return factory.getObject()
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory,
this.properties.getExecutorType())
public PageHelper pageHelper(DataSource dataSource) {
log.info("注册MyBatis分页插件PageHelper")
PageHelper pageHelper = new PageHelper()
Properties p = new Properties()
p.setProperty("offsetAsPageNum", "true")
p.setProperty("rowBoundsWithCount", "true")
p.setProperty("reasonable", "true")
pageHelper.setProperties(p)
return pageHelper
package org.springboot.sample.config.mybatis
import java.util.Properties
import org.springframework.boot.autoconfigure.AutoConfigureAfter
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import tk.mybatis.spring.mapper.MapperScannerConfigurer
@Configuration
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MyBatisMapperScannerConfig {
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer()
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory")
mapperScannerConfigurer.setBasePackage("org.springboot.sample.mapper")
Properties properties = new Properties()
// 这里要特别注意,不要把MyMapper放到 basePackage 中,也就是不能同其他Mapper一样被扫描到。
properties.setProperty("mappers", MyMapper.class.getName())
properties.setProperty("notEmpty", "false")
properties.setProperty("IDENTITY", "MYSQL")
mapperScannerConfigurer.setProperties(properties)
return mapperScannerConfigurer
package org.springboot.sample.config.
import org.apache.ibatis.session.ExecutorT
import org.springframework.boot.context.properties.ConfigurationP
import org.springframework.core.io.R
* Configuration properties for Mybatis.
* Eddú Meléndez
@ConfigurationProperties(prefix = MybatisProperties.MYBATIS_PREFIX)
public class MybatisProperties {
public static final String MYBATIS_PREFIX = "mybatis";
* Config file path.
* Location of mybatis mapper files.
private Resource[] mapperL
* Package to scan domain objects.
private String typeAliasesP
* Package to scan handlers.
private String typeHandlersP
* Check the config file exists.
private boolean checkConfigLocation = false;
* Execution mode.
private ExecutorType executorType = ExecutorType.SIMPLE;
public String getConfig() {
return this.
public void setConfig(String config) {
this.config =
public Resource[] getMapperLocations() {
return this.mapperL
public void setMapperLocations(Resource[] mapperLocations) {
this.mapperLocations = mapperL
public String getTypeHandlersPackage() {
return this.typeHandlersP
public void setTypeHandlersPackage(String typeHandlersPackage) {
this.typeHandlersPackage = typeHandlersP
public String getTypeAliasesPackage() {
return this.typeAliasesP
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesP
public boolean isCheckConfigLocation() {
return this.checkConfigL
public void setCheckConfigLocation(boolean checkConfigLocation) {
this.checkConfigLocation = checkConfigL
public ExecutorType getExecutorType() {
return this.executorT
public void setExecutorType(ExecutorType executorType) {
this.executorType = executorT
package org.springboot.sample.config.
import tk.mybatis.mapper.common.M
import tk.mybatis.mapper.common.MySqlM
public interface MyMapper&T& extends Mapper&T&, MySqlMapper&T& {
三、属性配置文件
属性配置文件中和文章开头指定的文章一样配置,没有什么修改,下面粘贴出来:
mybatis.mapper-locations=classpath*:org/springboot/sample/mapper/sql/mysql/*Mapper.xml
mybatis.type-aliases-package=org.springboot.sample.entity
四、在业务Mapper中继承基础MyMapper接口
public interface StudentMapper extends MyMapper&Student& {
List&Student& likeName(String name);
Student getById(int id);
int add(Student stu);
String getNameById(int id);
然后在Service中使用即可,后面就没什么说的了。
public class StudentService {
@Autowired
private JdbcTemplate jdbcT
@Autowired
private StudentMapper studentM
@TargetDataSource(name="ds2")
public List&Student& likeName(String name){
return studentMapper.likeName(name);
public int testSave(){
Student stu = new Student();
stu.setAge(33);
stu.setName("测试新增");
stu.setSumScore("66");
stu.setAvgScore("22");
return studentMapper.insert(stu);
最后还有一点要说明,使用公共Mapper“可能”需要对实体类进行修改。如果你的实体字段和数据库字段不一致(或者实体名称和数据库表名不一致),这样才需要修改,例如:
* 学生实体
http://blog.csdn.net/catoop/
public class Student implements Serializable{
private int
@Column(name="SCORE_SUM")
private String sumS
@Column(name="SCORE_AVG")
private String avgS
private int
其他没有什么可说的了,请至少要到
把插件的其他说明再看一遍。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:2071235次
积分:17759
积分:17759
排名:第404名
原创:241篇
转载:40篇
译文:10篇
评论:703条
文章:22篇
阅读:390978
(2)(1)(1)(1)(2)(10)(12)(10)(25)(17)(17)(10)(13)(21)(12)(5)(1)(9)(4)(6)(8)(2)(3)(2)(5)(2)(6)(4)(2)(1)(2)(1)(2)(1)(7)(14)(7)(5)(3)(1)(2)(19)(9)(3)1361人阅读
spring(2)
一、注释配置和 XML 配置的适用场合
  是否有了这些 IOC 注释,我们就可以完全摒除原来 XML 配置的方式呢?答案是否定的。有以下几点原因:
  注释配置不一定在先天上优于 XML 配置。如果 Bean 的依赖关系是固定的,(如 Service 使用了哪几个 DAO 类),这种配置信息不会在部署时发生调整,那么注释配置优于 XML 配置;反之如果这种依赖关系会在部署时发生调整,XML 配置显然又优于注释配置,因为注释是对 Java 源代码的调整,您需要重新改写源代码并重新编译才可以实施调整。
  如果 Bean 不是自己编写的类(如 JdbcTemplate、SessionFactoryBean 等),注释配置将无法实施,此时 XML 配置是唯一可用的方式。
  注释配置往往是类级别的,而 XML 配置则可以表现得更加灵活。比如相比于 @Transaction 事务注释,使用 aop/tx 命名空间的事务配置更加灵活和简单。
  所以在实现应用中,我们往往需要同时使用注释配置和 XML 配置,对于类级别且不会发生变动的配置可以优先考虑注释配置;而对于那些第三方类以及容易发生调整的配置则应优先考虑使用 XML 配置。Spring 会在具体实施 Bean 创建和 Bean 注入之前将这两种配置方式的元信息融合在一起。
二、spring提供了非常多的注解,试图找到一些清单,以便对整体有些认识。一共找到了两遍相关内容,感觉不错
1、http://www.oschina.net/uploads/doc/annotations/javax.html
2、,原文如下:
Guides you through all annotations supported in Spring 2.5, covering Core Spring Annotations, Spring MVC Annotations, and more.
Spring Annotations
From its beginning, Spring's most common means of configuration has been XML-based. But as developers grow weary of navigating through a seemingly endless maze of angle-brackets, some have started looking for other
ways to wire the beans in their Spring-enabled applications. Spring has responded with several annotation-driven configuration options. In this reference card, you'll find a guide to all of the annotations supported in Spring 2.5.
Core Spring Annotations
Context Configuration Annotations
These annotations are used by Spring to guide creation and injection of beans.
ANNOTATION
DESCRIPTION
@Autowired
Constructor, Field, Method
Declares a constructor, field, setter method, or configuration method to be autowired by type. Items annotated with @Autowired do not have to be public.
@Configurable
Used with &context:springconfigured& to declare types whose properties should be injected, even if they are not instantiated by Spring. Typically used to inject the properties of domain objects.
Type, Method, Field
Defines ordering, as an alternative to implementing the org. springframework.core.Ordered interface.
@Qualifier
Field, Parameter, Type, Annotation Type
Guides autowiring to be performed by means other than by type.
Method (setters)
Specifies that a particular property must be injected or else the configuration will fail.
Specifies the scope of a bean, either singleton, prototype, request, session, or some custom scope.
Autowiring Bean Properties
A typical Spring bean might have its properties wired something like this:
&bean id=&pirate& class=&Pirate&& &constructor-arg value=&Long John Silver& /& &property name=&treasureMap& ref=&treasureMap& /& &/bean&
But it's also possible to have Spring automatically inject a bean's properties from other beans in the context. For example, if the Pirate class were annotated with @Autowired like this...
public class Pirate { private S private TreasureMap treasureM public Pirate(String name) { this.name = } @Autowired public void setTreasureMap(TreasureMap treasureMap) { this.treasureMap = treasureM } }
...and if you were to configure annotation configuration in Spring using the &context:annotation-configuration& element like this...
&beans ... & &bean id=&pirate& class=&Pirate&& &constructor-arg value=&Long John Silver& /& &/bean& &bean id=&treasureMap& class=&TreasureMap& /& &context:annotation-config /& &/beans&
...then the &treasureMap& property will be automatically injected with a reference to a bean whose type is assignable to TreasureMap (in this case, the bean whose ID is &treasureMap&).
Autowiring Without Setter Methods
@Autowired can be used on any method (not just setter methods). The wiring can be done through any method, as illustrated here:
@Autowired public void directionsToTreasure(TreasureMap treasureMap) { this.treasureMap = treasureM }
And even on member variables:
@Autowired private TreasureMap treasureM
To resolve any autowiring ambiguity, use the @Qualifier attribute with @Autowired.
@Autowired @Qualifier(&mapToTortuga&) private TreasureMap treasureM
Ensuring That Required Properties are Set
To ensure that a property is injected with a value, use the @Required annotation:
@Required public void setTreasureMap(TreasureMap treasureMap) { this.treasureMap = treasureM }
In this case, the &treasureMap& property must be injected or else Spring will throw a BeanInitializationException and context creation will fail.
Stereotyping Annotations
These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application
context if &context:component-scan& is in the Spring XML configuration.
In addition, if a PersistenceExceptionTranslationPostProcessor is configured in Spring, any bean annotated with @Repository will have SQLExceptions thrown from its methods translated into one of Spring's unchecked
DataAccessExceptions.
ANNOTATION
DESCRIPTION
@Component
Generic stereotype annotation for any Spring-managed component.
@Controller
Stereotypes a component as a Spring MVC controller.
@Repository
Stereotypes a component as a repository. Also indicates that SQLExceptions thrown from the component's methods should be translated into Spring DataAccessExceptions.
Stereotypes a component as a service.
Automatically Configuring Beans
In the previous section, you saw how to automatically wire a bean's properties using the @Autowired annotation. But it is possible to take autowiring to a new level by automatically registering beans in Spring.
To get started with automatic registration of beans, first annotate the bean with one of the stereotype annotations, such as @Component:
@Component public class Pirate { private S private TreasureMap treasureM public Pirate(String name) { this.name = } @Autowired public void setTreasureMap(TreasureMap treasureMap) { this.treasureMap = treasureM } }
Then add &context:component-scan& to your Spring XML configuration:
&context:component-scan base-package=&com.habuma.pirates& /&
The base-package annotation tells Spring to scan com.habuma. pirates and all of its subpackages for beans to automatically register.
You can specify a name for the bean by passing it as the value of @Component.
@Component(&jackSparrow&) public class Pirate { ... }
Specifying Scope For Auto-Configured Beans
By default, all beans in Spring, including auto-configured beans, are scoped as singleton. But you can specify the scope using the @Scope annotation. For example:
@Component @Scope(&prototype&) public class Pirate { ... }
This specifies that the pirate bean be scoped as a prototype bean.
Creating Custom Stereotypes
Autoregistering beans is a great way to cut back on the amount of XML required to configure Spring. But it may bother you that your autoregistered classes are annotated with Spring-specific annotations. If you're
looking for a more non-intrusive way to autoregister beans, you have two options:
Create your own custom stereotype annotation. Doing so is as simple as creating a custom annotation that is itself annotated with @Component:
@Component public @interface MyComponent { String value() default &&; }
Or add a filter to &context:component-scan& to scan for annotations that it normally would not:
&context:component-scan base-package=&com.habuma.pirates&& &context:include-filter type=&annotation& expression=&com.habuma.MyComponent& /& &context:exclude-filter type=&annotation& expression= &org.ponent& /& &/context:component-scan&
In this case, the @MyComponent custom annotation has been added to the list of annotations that are scanned for, but @Component has been excluded (that is, @Componentannotated classes will no longer be autoregistered).
Regardless of which option you choose, you should be able to autoregister beans by annotating their classes with the custom annotation:
@MyComponent public class Pirate {...}
Spring MVC Annotations
These annotations were introduced in Spring 2.5 to make it easier to create Spring MVC applications with minimal XML configuration and without extending one of the many implementations of the Controller interface.
ANNOTATION
DESCRIPTION
@Controller
Stereotypes a component as a Spring MVC controller.
@InitBinder
Annotates a method that customizes data binding.
@ModelAttribute
Parameter, Method
When applied to a method, used to preload the model with the value returned from the method. When applied to a parameter, binds a model attribute to the parameter. table
@RequestMapping
Method, Type
Maps a URL pattern and/or HTTP method to a method or controller type.
@RequestParam
Binds a request parameter to a method parameter.
@SessionAttributes
Specifies that a model attribute should be stored in the session.
Setting up Spring for Annotated Controllers
Before we can use annotations on Spring MVC controllers, we'll need to add a few lines of XML to tell Spring that our controllers will be annotation-driven. First, so that we won't have to register each of our controllers
individually as &bean&s, we'll need a &context:component-scan&:
&context:component-scan base-package=&com.habuma.pirates.mvc&/&
In addition to autoregistering @Component-annotated beans, &context:component-scan& also autoregisters beans that are annotated with @Controller. We'll see a few examples of @Controller-annotated classes in a moment.
But first, we'll also need to tell Spring to honor the other Spring MVC annotations. For that we'll need &context:annotation-config& : &context:annotation-config/&
Use a conventions-based view resolver.
If you use a conventions-based view resolver, such as Spring's UrlBasedViewResolver or InternalResourceViewResolver, along with &context:component-scan& and &context:annotation-config&, you can grow your application
indefinitely without ever touching the Spring XML again.
Creating a Simple MVC Controller
The following HomePage class is annotated to function as a Spring MVC controller:
@Controller @RequestMapping(&/home.htm&) public class HomePage { @RequestMapping(method = RequestMethod.GET) public String showHomePage(Map model) { List&Pirate& pirates = pirateService. getPirateList(); model.add(&pirateList&, pirates); return &home&; } @Autowired PirateService pirateS }
There are several important things to point out here. First, the HomePage class is annotated with @Controller so that it will be autoregistered as a bean by &context:component-scan&. It is also annotated with @RequestMapping,
indicating that this controller will respond to requests for &/home.htm&.
Within the class, the showHomePage() method is also annotated with @RequestMapping. In this case, @RequestMapping indicates that HTTP GET requests to &/home.htm& will be handled by the showHomePage() method.
Creating a Form-Handling Controller
In a pre-2.5 Spring MVC application, form-processing controllers would typically extend SimpleFormController (or some similar base class). But with Spring 2.5, a form-processing controller just has a method that
is annotated to handle the HTTP POST request:
@Controller @RequestMapping(&/addPirate.htm&) public class AddPirateFormController { @RequestMapping(method = RequestMethod.GET) public String setupForm(ModelMap model) { return &addPirate&; } @ModelAttribute(&pirate&) public Pirate setupPirate() { Pirate pirate = new Pirate(); } @RequestMapping(method = RequestMethod.POST) protected String addPirate(@ModelAttribute(&pirate&) Pirate pirate) { pirateService.addPirate(pirate); return &pirateAdded&; } @Autowired PirateService pirateS }
Here the @RequestMapping annotation is applied to two different methods. The setupForm() method is annotated to handle HTTP GET requests while the addPirate() method will handle HTTP POST requests. Meanwhile, the
@ModelAttribute is also pulling double duty by populating the model with a new instance of Pirate before the form is displayed and then pulling the Pirate from the model so that it can be given to addPirate() for processing.
Transaction Annotations
The @Transactional annotation is used along with the &tx:annotation-driven& element to declare transactional boundaries and rules as class and method metadata in Java.
ANNOTATION
DESCRIPTION
@Transactional
Method, Type
Declares transactional boundaries and rules on a bean and/or its methods.
Annotating Transactional Boundaries
To use Spring's support for annotation-declared transactions, you'll first need to add a small amount of XML to the Spring configuration:
&?xml version=&1.0& encoding=&UTF-8&?& &beans xmlns=&http://www.springframework.org/schema/ beans& xmlns:tx=&http://www.springframework.org/schema/tx& xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance& xsi:schemaLocation=&http://www.springframework.org/ schema/beans http://www.springframework.org/schema/beans/ springbeans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx- 2.5.xsd&& &tx:annotation-driven /& ... &/beans&
The &tx:annotation-driven& element tells Spring to keep an eye out for beans that are annotated with @Transactional. In addition, you'll also need a platform transaction manager bean declared in the Spring context.
For example, if your application uses Hibernate, you'll want to include the HibernateTransactionManager:
&bean id=&transactionManager& class=&org.springframework.orm.hibernate3. HibernateTransactionManager&& &property name=&sessionFactory& ref=&sessionFactory& /& &/bean&
With the basic plumbing in place, you're ready to start annotating the transactional boundaries:
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true) public class TreasureRepositoryImpl implements TreasureRepository { ... @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public void storeTreasure(Treasure treasure) {...} ... }
At the class level, @Transactional is declaring that all methods should support transactions and be read-only. But, at the method-level, @Transactional declares that the storeTreasure() method requires a transaction
and is not read-only. Note that for transactions to be applied to @Transactionalannotated classes, those classes must be wired as beans in Spring.
JMX Annotations
These annotations, used with the &context:mbean-export& element, declare bean methods and properties as MBean operations and attributes.
ANNOTATIONS
DESCRIPTION
@ManagedAttribute
Used on a setter or getter method to indicate that the bean's property should be exposed as a MBean attribute.
@ManagedNotification
Indicates a JMX notification emitted by a bean.
@ManagedNotifications
Indicates the JMX notifications emitted by a bean.
@ManagedOperation
Specifies that a method should be exposed as a MBean operation.
@ManagedOperationParameter
Used to provide a description for an operation parameter.
@ManagedOperationParameters
Provides descriptions for one or more operation parameters.
@ManagedResource
Specifies that all instances of a class should be exposed a MBeans.
Exposing a Spring Bean as a MBean
To get started with Spring-annotated MBeans, you'll need to include &context:mbean-export& in the Spring XML configuration:
&context:mbean-export/&
Then, you can annotate any of your Spring-managed beans to be exported as MBeans:
@ManagedResource(objectName=&pirates:name=PirateService&) public interface PirateService { @ManagedOperation( description=&Get the pirate list&) public List&Pirate& getPirateList(); }
Here, the PirateService has been annotated to be exported as a MBean and its getPirateList() method is a managed operation.
Aspect Annotations
For defining aspects, Spring leverages the set of annotations provided by AspectJ.
ANNOTATION
DESCRIPTION
Declares a class to be an aspect.
Declares a method to be called after a pointcut completes.
@AfterReturning
Declares a method to be called after a pointcut returns successfully.
@AfterThrowing
Declares a method to be called after a pointcut throws an exception.
Declares a method that will wrap the pointcut.
Declares a method to be called before proceeding to the pointcut.
@DeclareParents
Static Field
Declares that matching types should be given new parents,that is, it introduces new functionality into matching types.
Declares an empty method as a pointcut placeholder method.
What's important to note, however, is that while you can use AspectJ annotations to define Spring aspects, those aspects will be defined in the context of Spring AOP and will not be handled by the AspectJ runtime.
This is significant because Spring AOP is limited to proxying method invocations and does not provide for the more exotic pointcuts (constructor interception, field interception, etc.) offered by AspectJ.
Annotating Aspects
To use AspectJ annotations to create Spring aspects, you'll first need to provide a bit of Spring XML plumbing:
&beans xmlns=&http://www.springframework.org/schema/ beans& xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance& xmlns:aop=&http://www.springframework.org/schema/aop& xsi:schemaLocation=&http://www.springframework.org/ schema/beans http://www.springframework.org/schema/beans/ spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/springaop- 2.5.xsd&& ... &aop:aspectj-autoproxy/& ... &/beans&
The &aop:aspectj-autoproxy& element tells Spring to watch for beans annotated with AspectJ annotations and, if it finds any, to use them to create aspects. Then you can annotate bean classes to be aspects:
@Aspect public class ChantySinger { @Pointcut(&execution(* Pirate.plunder(..))&) public void plunderPC() {} @Before(&plunderPC()&) public void singYoHo() { ... } @AfterReturning(&plunderPC()&) public void singAPiratesLifeForMe() { ... } }
This simple annotation-based aspect has a pointcut that is triggered by the execution of a plunder() method on the Pirate class. Before the Pirate.plunder() method is executed, the singYoHo() method is called. Then,
after the Pirate.plunder() method returns successfully, the singAPiratesLifeForMe() method is invoked. (For more advanced examples of AspectJ annotations, see the AspectJ documentation at&.)
Note the rather odd looking plunderPC() method. It is annotated with @Pointcut to indicate that this method is a pointcut placeholder. The key thing here is that the most interesting stuff happens in the annotation
itself and not in the method. In fact, pointcut placeholder methods must be empty methods and return void.
JSR-250 Annotations
In addition to Spring's own set of annotations, Spring also supports a few of the annotations defined by JSR-250, which is the basis for the annotations used in EJB 3.
ANNOTATION
DESCRIPTION
@PostConstruct
Indicates a method to be invoked after a bean has been created and dependency injection is complete. Used to perform any initialization work necessary.
@PreDestroy
Indicates a method to be invoked just before a bean is removed from the Spring context. Used to perform any cleanup work necessary.
Method, Field
Indicates that a method or field should be injected with a named resource (by default, another bean).
Wiring Bean Properties with @Resource
Using @Resource, you can wire a bean property by name:
public class Pirate { @Resource private TreasureMap treasureM }
In this case, Spring will attempt to wire the &treasureMap& property with a reference to a bean whose ID is &treasureMap&. If you'd rather explicitly choose another bean to wire into the property, specify it to
the name attribute:
public class Pirate { @Resource(name=&mapToSkullIsland&) private TreasureMap treasureM }
Initialization and Destruction Methods
Using JSR-250's @PostConstruct and @PreDestroy methods, you can declare methods that hook into a bean's lifecycle. For example, consider the following methods added to the Pirate class:
public class Pirate { ... @PostConstruct public void wakeUp() { System.out.println(&Yo ho!&); } @PreDestroy public void goAway() { System.out.println(&Yar!&); } }
As annotated, the wakeUp() method will be invoked just after Spring instantiates the bean and goAway() will be invoked just before the bean is removed from the Spring container.
Testing Annotations
These annotations are useful for creating unit tests in the JUnit 4 style that depend on Spring beans and/or require a transactional context.
ANNOTATION
DESCRIPTION
@AfterTransaction
Used to identify a method to be invoked after a transaction has completed.
@BeforeTransaction
Used to identify a method to be invoked before a transaction starts.
@ContextConfiguration
Configures a Spring application context for a test.
@DirtiesContext
Indicates that a method dirties the Spring container and thus it must be rebuilt after the test completes.
@ExpectedException
Indicates that the test method is expected to throw a specific exception. The test will fail if the exception is not thrown.
@IfProfileValue
Type, Method
Indicates that the test class or method is enabled for a specific profile configuration.
@NotTransactional
Indicates that a test method must not execute in a transactional context.
@ProfileValueSourceConfiguration
Identifies an implementation of a profile value source. The absence of this annotation will cause profile values to be loaded from system properties.
Indicates that the test method must be repeated a specific number of times.
Specifies whether or not the transaction for the annotated method should be rolled back or not.
@TestExecutionListeners
Identifies zero or more test execution listeners for a test class.
Specifies a time limit for the test method. If the test does not complete before the time has expired, the test will fail.
@TransactionConfiguration
Configures test classes for transactions, specifying the transaction manager and/or the default rollback rule for all test methods in a test class.
Writing a Spring-Aware Test
The key to writing a Spring-aware test is to annotate the test class with @RunWith, specifying SpringJUnit4ClassRunner as the class runner behind the test:
@RunWith(SpringJUnit4ClassRunner.class) public class PirateTest { ... }
In this case, the Spring test runner will try to load a Spring application context from a file named PirateTest-context.xml. If you'd rather specify one or more XML files to load the application context from, you
can do that with @ContextConfiguration:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { &pirates.xml& }) public class PirateTest { ... }
With test configured to load a Spring application context, you now may request that Spring autowire properties of the test class with beans from the Spring context:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { &pirates.xml& }) public class PirateTest { @Autowired private P @Autowired private TreasureMap treasureM @Test public void annotatedPropertyShouldBeAutowired() { assertNotNull(pirate.getTreasureMap()); assertEquals(treasureMap, pirate.getTreasureMap()); } }
In this case, the pirate and treasureMap properties will be wired with the beans whose ID are &pirate& and &treasureMap&, respectively.
Accessing the Spring Context in a Test
If you need the Spring application context itself in a test, you can autowire it into the test the same as if it were a bean in the context:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { &pirates.xml& }) public class PirateTest { @Autowired private P @Autowired private ApplicationContext applicationC @Test public void annotatedPropertyShouldBeAutowired() { assertNotNull(pirate.getTreasureMap()); assertEquals(applicationContext. getBean(&treasureMap&), pirate .getTreasureMap()); } }
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:3991次
排名:千里之外
(1)(1)(4)(1)(1)(1)(1)

我要回帖

更多关于 autoconfigureafter 的文章

 

随机推荐