Annotation Type @bean,@Import,@configuration使用--官方文档
@Target(value={METHOD,ANNOTATION_TYPE})
@Retention(value=RUNTIME)
@Documented
public @interface BeanIndicates that a method produces a bean to be managed by the Spring container.Overview
The names and semantics of the attributes to this annotation are intentionally similar to those of the
<bean/>element in the Spring XML schema. For example:@Bean
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;
}Bean Names
While a
nameattribute is available, the default strategy for determining the name of a bean is to use the name of the@Beanmethod. This is convenient and intuitive, but if explicit naming is desired, thenameattribute may be used. Also note thatnameaccepts an array of Strings. This is in order to allow for specifying multiple names (i.e., aliases) for a single bean.@Bean(name={"b1","b2"}) // bean available as 'b1' and 'b2', but not 'myBean'
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;
}Scope, DependsOn, Primary, and Lazy
Note that the
@Beanannotation does not provide attributes for scope, depends-on, primary, or lazy. Rather, it should be used in conjunction with@Scope,@DependsOn,@Primary, and@Lazyannotations to achieve those semantics. For example:@Bean
@Scope("prototype")
public MyBean myBean() {
// instantiate and configure MyBean obj
return obj;
}@BeanMethods in@ConfigurationClassesTypically,
@Beanmethods are declared within@Configurationclasses. In this case, bean methods may reference other@Beanmethods in the same class by calling them directly. This ensures that references between beans are strongly typed and navigable. Such so-called 'inter-bean references' are guaranteed to respect scoping and AOP semantics, just likegetBean()lookups would. These are the semantics known from the original 'Spring JavaConfig' project which require CGLIB subclassing of each such configuration class at runtime. As a consequence,@Configurationclasses and their factory methods must not be marked as final or private in this mode. For example:@Configuration
public class AppConfig {
@Bean
public FooService fooService() {
return new FooService(fooRepository());
}
@Bean
public FooRepository fooRepository() {
return new JdbcFooRepository(dataSource());
}
// ...
}@BeanLite Mode@Beanmethods may also be declared within classes that are not annotated with@Configuration. For example, bean methods may be declared in a@Componentclass or even in a plain old class. In such cases, a@Beanmethod will get processed in a so-called 'lite' mode.Bean methods in lite mode will be treated as plain factory methods by the container (similar to
factory-methoddeclarations in XML), with scoping and lifecycle callbacks properly applied. The containing class remains unmodified in this case, and there are no unusual constraints for the containing class or the factory methods.In contrast to the semantics for bean methods in
@Configurationclasses, 'inter-bean references' are not supported in lite mode. Instead, when one@Bean-method invokes another@Bean-method in lite mode, the invocation is a standard Java method invocation; Spring does not intercept the invocation via a CGLIB proxy. This is analogous to inter-@Transactionalmethod calls where in proxy mode, Spring does not intercept the invocation — Spring does so only in AspectJ mode.For example:
@Component
public class Calculator {
public int sum(int a, int b) {
return a+b;
} @Bean
public MyBean myBean() {
return new MyBean();
}
}Bootstrapping
See @
ConfigurationJavadoc for further details including how to bootstrap the container usingAnnotationConfigApplicationContextand friends.BeanFactoryPostProcessor-returning@BeanmethodsSpecial consideration must be taken for
@Beanmethods that return SpringBeanFactoryPostProcessor(BFPP) types. BecauseBFPPobjects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as@Autowired,@Value, and@PostConstructwithin@Configurationclasses. To avoid these lifecycle issues, markBFPP-returning@Beanmethods asstatic. For example:@Bean
public static PropertyPlaceholderConfigurer ppc() {
// instantiate, configure and return ppc ...
}By marking this method as
static, it can be invoked without causing instantiation of its declaring@Configurationclass, thus avoiding the above-mentioned lifecycle conflicts. Note however thatstatic@Beanmethods will not be enhanced for scoping and AOP semantics as mentioned above. This works out inBFPPcases, as they are not typically referenced by other@Beanmethods. As a reminder, a WARN-level log message will be issued for any non-static@Beanmethods having a return type assignable toBeanFactoryPostProcessor.
Optional Element Summary
Optional Elements Modifier and Type Optional Element and Description AutowireautowireAre dependencies to be injected via convention-based autowiring by name or type?StringdestroyMethodThe optional name of a method to call on the bean instance upon closing the application context, for example aclose()method on a JDBCDataSourceimplementation, or a HibernateSessionFactoryobject.StringinitMethodThe optional name of a method to call on the bean instance during initialization.String[]nameThe name of this bean, or if plural, aliases for this bean.
Element Detail
name
public abstract String[] name
The name of this bean, or if plural, aliases for this bean. If left unspecified the name of the bean is the name of the annotated method. If specified, the method name is ignored.- Default:
- {}
autowire
public abstract Autowire autowire
Are dependencies to be injected via convention-based autowiring by name or type?- Default:
- org.springframework.beans.factory.annotation.Autowire.NO
initMethod
public abstract String initMethod
The optional name of a method to call on the bean instance during initialization. Not commonly used, given that the method may be called programmatically directly within the body of a Bean-annotated method.The default value is
"", indicating no init method to be called.- Default:
- ""
destroyMethod
public abstract String destroyMethod
The optional name of a method to call on the bean instance upon closing the application context, for example aclose()method on a JDBCDataSourceimplementation, or a HibernateSessionFactoryobject. The method must have no arguments but may throw any exception.As a convenience to the user, the container will attempt to infer a destroy method against an object returned from the
@Beanmethod. For example, given an@Beanmethod returning an Apache Commons DBCPBasicDataSource, the container will notice theclose()method available on that object and automatically register it as thedestroyMethod. This 'destroy method inference' is currently limited to detecting only public, no-arg methods named 'close' or 'shutdown'. The method may be declared at any level of the inheritance hierarchy and will be detected regardless of the return type of the@Beanmethod (i.e., detection occurs reflectively against the bean instance itself at creation time).To disable destroy method inference for a particular
@Bean, specify an empty string as the value, e.g.@Bean(destroyMethod=""). Note that theDisposableBeanand theCloseable/AutoCloseableinterfaces will nevertheless get detected and the corresponding destroy/close method invoked.Note: Only invoked on beans whose lifecycle is under the full control of the factory, which is always the case for singletons but not guaranteed for any other scope.
- See Also:
ConfigurableApplicationContext.close()
- Default:
- "(inferred)
官方地址:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html
http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
Annotation Type Import
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
public @interface ImportIndicates one or more@Configurationclasses to import.Provides functionality equivalent to the
<import/>element in Spring XML. Only supported for classes annotated with@Configurationor declaring at least one@Beanmethod, as well asImportSelectorandImportBeanDefinitionRegistrarimplementations.@Beandefinitions declared in imported@Configurationclasses should be accessed by using@Autowiredinjection. Either the bean itself can be autowired, or the configuration class instance declaring the bean can be autowired. The latter approach allows for explicit, IDE-friendly navigation between@Configurationclass methods.May be declared at the class level or as a meta-annotation.
If XML or other non-
@Configurationbean definition resources need to be imported, use@ImportResource官方地址:http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Import.html
Annotation Type Configuration
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface ConfigurationIndicates that a class declares one or more@Beanmethods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
// instantiate, configure and return bean ...
}
}Bootstrapping
@ConfigurationclassesVia
AnnotationConfigApplicationContext@Configurationclasses are typically bootstrapped using eitherAnnotationConfigApplicationContextor its web-capable variant,AnnotationConfigWebApplicationContext. A simple example with the former follows:AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext();
ctx.register(AppConfig.class);
ctx.refresh();
MyBean myBean = ctx.getBean(MyBean.class);
// use myBean ...See
AnnotationConfigApplicationContextJavadoc for further details and seeAnnotationConfigWebApplicationContextforweb.xmlconfiguration instructions.Via Spring
<beans>XMLAs an alternative to registering
@Configurationclasses directly against anAnnotationConfigApplicationContext,@Configurationclasses may be declared as normal<bean>definitions within Spring XML files:<beans>
<context:annotation-config/>
<bean class="com.acme.AppConfig"/>
</beans>In the example above,
<context:annotation-config/>is required in order to enableConfigurationClassPostProcessorand other annotation-related post processors that facilitate handling@Configurationclasses.Via component scanning
@Configurationis meta-annotated with@Component, therefore@Configurationclasses are candidates for component scanning (typically using Spring XML's<context:component-scan/>element) and therefore may also take advantage of@Autowired/@Injectat the field and method level (but not at the constructor level).@Configurationclasses may not only be bootstrapped using component scanning, but may also themselves configure component scanning using the@ComponentScanannotation:@Configuration
@ComponentScan("com.acme.app.services")
public class AppConfig {
// various @Bean definitions ...
}See
@ComponentScanJavadoc for details.Working with externalized values
Using the
EnvironmentAPIExternalized values may be looked up by injecting the Spring
Environmentinto a@Configurationclass using the@Autowiredor the@Injectannotation:@Configuration
public class AppConfig {
@Inject Environment env; @Bean
public MyBean myBean() {
MyBean myBean = new MyBean();
myBean.setName(env.getProperty("bean.name"));
return myBean;
}
}Properties resolved through the
Environmentreside in one or more "property source" objects, and@Configurationclasses may contribute property sources to theEnvironmentobject using the@PropertySourcesannotation:@Configuration
@PropertySource("classpath:/com/acme/app.properties")
public class AppConfig {
@Inject Environment env; @Bean
public MyBean myBean() {
return new MyBean(env.getProperty("bean.name"));
}
}See
Environmentand@PropertySourceJavadoc for further details.Using the
@ValueannotationExternalized values may be 'wired into'
@Configurationclasses using the@Valueannotation:@Configuration
@PropertySource("classpath:/com/acme/app.properties")
public class AppConfig {
@Value("${bean.name}") String beanName; @Bean
public MyBean myBean() {
return new MyBean(beanName);
}
}This approach is most useful when using Spring's
PropertySourcesPlaceholderConfigurer, usually enabled via XML with<context:property-placeholder/>. See the section below on composing@Configurationclasses with Spring XML using@ImportResource, see@ValueJavadoc, and see@BeanJavadoc for details on working withBeanFactoryPostProcessortypes such asPropertySourcesPlaceholderConfigurer.Composing
@ConfigurationclassesWith the
@Importannotation@Configurationclasses may be composed using the@Importannotation, not unlike the way that<import>works in Spring XML. Because@Configurationobjects are managed as Spring beans within the container, imported configurations may be injected using@Autowiredor@Inject:@Configuration
public class DatabaseConfig {
@Bean
public DataSource dataSource() {
// instantiate, configure and return DataSource
}
} @Configuration
@Import(DatabaseConfig.class)
public class AppConfig {
@Inject DatabaseConfig dataConfig; @Bean
public MyBean myBean() {
// reference the dataSource() bean method
return new MyBean(dataConfig.dataSource());
}
}Now both
AppConfigand the importedDatabaseConfigcan be bootstrapped by registering onlyAppConfigagainst the Spring context:new AnnotationConfigApplicationContext(AppConfig.class);
With the
@Profileannotation@Configurationclasses may be marked with the@Profileannotation to indicate they should be processed only if a given profile or profiles are active:@Profile("embedded")
@Configuration
public class EmbeddedDatabaseConfig {
@Bean
public DataSource dataSource() {
// instantiate, configure and return embedded DataSource
}
} @Profile("production")
@Configuration
public class ProductionDatabaseConfig {
@Bean
public DataSource dataSource() {
// instantiate, configure and return production DataSource
}
}See
@ProfileandEnvironmentJavadoc for further details.With Spring XML using the
@ImportResourceannotationAs mentioned above,
@Configurationclasses may be declared as regular Spring<bean>definitions within Spring XML files. It is also possible to import Spring XML configuration files into@Configurationclasses using the@ImportResourceannotation. Bean definitions imported from XML can be injected using@Autowiredor@Import:@Configuration
@ImportResource("classpath:/com/acme/database-config.xml")
public class AppConfig {
@Inject DataSource dataSource; // from XML @Bean
public MyBean myBean() {
// inject the XML-defined dataSource bean
return new MyBean(this.dataSource);
}
}With nested
@Configurationclasses@Configurationclasses may be nested within one another as follows:@Configuration
public class AppConfig {
@Inject DataSource dataSource; @Bean
public MyBean myBean() {
return new MyBean(dataSource);
} @Configuration
static class DatabaseConfig {
@Bean
DataSource dataSource() {
return new EmbeddedDatabaseBuilder().build();
}
}
}When bootstrapping such an arrangement, only
AppConfigneed be registered against the application context. By virtue of being a nested@Configurationclass,DatabaseConfigwill be registered automatically. This avoids the need to use an@Importannotation when the relationship betweenAppConfigDatabaseConfigis already implicitly clear.Note also that nested
@Configurationclasses can be used to good effect with the@Profileannotation to provide two options of the same bean to the enclosing@Configurationclass.Configuring lazy initialization
By default,
@Beanmethods will be eagerly instantiated at container bootstrap time. To avoid this,@Configurationmay be used in conjunction with the@Lazyannotation to indicate that all@Beanmethods declared within the class are by default lazily initialized. Note that@Lazymay be used on individual@Beanmethods as well.Testing support for
@ConfigurationclassesThe Spring TestContext framework available in the
spring-testmodule provides the@ContextConfigurationannotation, which as of Spring 3.1 can accept an array of@ConfigurationClassobjects:@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfig.class, DatabaseConfig.class})
public class MyTests { @Autowired MyBean myBean; @Autowired DataSource dataSource; @Test
public void test() {
// assertions against myBean ...
}
}See TestContext framework reference documentation for details.
Enabling built-in Spring features using
@EnableannotationsSpring features such as asynchronous method execution, scheduled task execution, annotation driven transaction management, and even Spring MVC can be enabled and configured from
@Configurationclasses using their respective "@Enable" annotations. See@EnableAsync,@EnableScheduling,@EnableTransactionManagement,@EnableAspectJAutoProxy, and@EnableWebMvcfor details.Constraints when authoring
@Configurationclasses- @Configuration classes must be non-final
- @Configuration classes must be non-local (may not be declared within a method)
- @Configuration classes must have a default/no-arg constructor and may not use
@Autowiredconstructor parameters. Any nested configuration classes must bestatic.
官方地址:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html
Annotation Type @bean,@Import,@configuration使用--官方文档的更多相关文章
- Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(二)
接前一篇 Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 本篇主要内容:Spring Type Conver ...
- Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion
本篇太乱,请移步: Spring Framework 官方文档学习(四)之Validation.Data Binding.Type Conversion(一) 写了删删了写,反复几次,对自己的描述很不 ...
- Spring Framework 官方文档学习(四)之Validation、Data Binding、Type Conversion(一)
题外话:本篇是对之前那篇的重排版.并拆分成两篇,免得没了看的兴趣. 前言 在Spring Framework官方文档中,这三者是放到一起讲的,但没有解释为什么放到一起.大概是默认了读者都是有相关经验的 ...
- Spring Framework 官方文档学习(二)之IoC容器与bean lifecycle
到目前为止,已经看了一百页.再次感慨下,如果想使用Spring,那可以看视频或者找例子,但如果想深入理解Spring,最好还是看官方文档. 原计划是把一些基本接口的功能.层次以及彼此的关系罗列一下.同 ...
- TestNG官方文档中文版(2)-annotation
TestNG的官方文档的中文翻译版第二章,原文请见 http://testng.org/doc/documentation-main.html 2 - Annotation 这里是TestNG中用到的 ...
- TestNG官方文档中文版(2)-annotation(转)
1. 介绍 TestNG是一个设计用来简化广泛的测试需求的测试框架,从单元测试(隔离测试一个类)到集成测试(测试由有多个类多个包甚至多个外部框架组成的整个系统,例如运用服务器). 编写一个测试的 ...
- 微信小程序官方文档中表单组建button部分有关function(type)中type的个人理解
官方文档关于button组件的简介 xml页面挺容易理解,但js部分起初对整体写的形式都不太理解,随着逐渐阅读代码基本理解了 xml页面代码: <button type="defaul ...
- Spring 4 官方文档学习(十四)WebSocket支持
个人提示:如果需要用到页面推送,高频且要低延迟,WebSocket无疑是最佳选择.否则还是轮询和long polling吧. 做了一个小demo放在码云上,有兴趣的可以看一下,简单易懂:websock ...
- Spring JMS 官方文档学习
最后部分的XML懒得写了,因为个人更倾向于JavaConfig形式. 为知笔记版本见这里,带格式~ 做了一个小demo,放到码云上了,有兴趣的点我. 说明:需要先了解下JMS的基础知识. 1.介绍 S ...
随机推荐
- POJ 3083 Children of the Candy Corn bfs和dfs
Children of the Candy Corn Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8102 Acc ...
- 学习总结之Log4NET
通过在网上查找了一些资料,用了些时间学习了log4NET,做了一个小小的总结,说一下它的特点吧 首先呢log4NET是.Net下一个非常优秀的开源日志记录组件.它可以将日志分成不同等级,也可以按照我们 ...
- 滴滴过节送10元打车券是不是bug
自从滴滴跟快的去年合作以后,也不玩烧钱大战了,也没法打到免费的车了,乘客打车优惠也少了. 但是现在的滴滴在过节的时候还是会返滴滴代金券,而且金额都比较大,超出了打车的起步价.半年前这边的司机会经常利用 ...
- bzoj 2226: [Spoj 5971] LCMSum 数论
2226: [Spoj 5971] LCMSum Time Limit: 20 Sec Memory Limit: 259 MBSubmit: 578 Solved: 259[Submit][St ...
- 转:char*, char[] ,CString, string的转换
转:char*, char[] ,CString, string的转换 (一) 概述 string和CString均是字符串模板类,string为标准模板类(STL)定义的字符串类,已经纳入C++标准 ...
- Hibernate 注解多对一 要求在多那边产生一个外键而不会另外产生一个表
在使用hibernate注解的时候,我们映射一对多时,有时候莫名其妙的产生了两张表,其中一张表是A_B,这并不符合数据库中多的一方放置一个外键的原则,那么如何控制只产生一个表呢,请看下面的例子: 多的 ...
- 【HDOJ】4612 Warm up
双连通缩点+求树的直径,图论基础题目. /* 4612 */ #pragma comment(linker, "/STACK:1024000000,1024000000") #in ...
- java学习面向对象之抽象类
什么是抽象类,之所以说抽象就是具体的反义词喽~抽象离我们最近的距离也就是初中的时候学过的美术课,抽象画派.拿一桶画彩就这么往画布上一泼,那就是抽象.那么java世界当中什么是抽象呢?我们再拿动物还有狗 ...
- (转载)函数:mysqli_query和mysql_query有何区别?
(转载)http://wzan315.blog.163.com/blog/static/37192636201241732045299/ Mysqli.dll是一个允许以对象的方式或者过程操作数据库的 ...
- Request.ServerVariables详细说明
客户端ip: Request.ServerVariables.Get("Remote_Addr").ToString(); 客户端主机名: Request.ServerVaria ...