PS: Spring boot注解,Configuration是生成一个config对象,@Bean指定对应的函数返回的是Bean对象,相当于XML定义,ConfigurationProperties是指定对应的函数返回的保护这些properties

http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

So far you have seen how we configure Spring beans using XML configuration file. If you are comfortable with XML configuration, then I will say it is really not required to learn how to proceed with Java based configuration because you are going to achieve the same result using either of the configurations available.

Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations explained below.

@Configuration & @Bean Annotations:

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context. The simplest possible @Configuration class would be as follows:

package com.tutorialspoint;
import org.springframework.context.annotation.*; @Configuration
public class HelloWorldConfig { @Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}

Above code will be equivalent to the following XML configuration:

<beans>
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld" />
</beans>

Here the method name annotated with @Bean works as bean ID and it creates and returns actual bean. Your configuration class can have declaration for more than one @Bean. Once your configuration classes are defined, you can load & provide them to Spring container using AnnotationConfigApplicationContext as follows:

public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}

You can load various configuration classes as follows:

public static void main(String[] args) {
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class, OtherConfig.class);
ctx.register(AdditionalConfig.class);
ctx.refresh(); MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}

Example:

Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:

Step Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org.
4 Create Java classes HelloWorldConfig, HelloWorld and MainApp under the com.tutorialspoint package.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

Here is the content of HelloWorldConfig.java file:

package com.tutorialspoint;
import org.springframework.context.annotation.*; @Configuration
public class HelloWorldConfig { @Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}

Here is the content of HelloWorld.java file:

package com.tutorialspoint;

public class HelloWorld {
private String message; public void setMessage(String message){
this.message = message;
} public void getMessage(){
System.out.println("Your Message : " + message);
}
}

Following is the content of the MainApp.java file:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*; public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(HelloWorldConfig.class); HelloWorld helloWorld = ctx.getBean(HelloWorld.class); helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
}
}

Once you are done with creating all the source filesand adding required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, this will print the following message:

Your Message : Hello World!

Injecting Bean Dependencies:

When @Beans have dependencies on one another, expressing that dependency is as simple as having one bean method calling another as follows:

package com.tutorialspoint;
import org.springframework.context.annotation.*; @Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}

Here, the foo bean receives a reference to bar via constructor injection. Now let us see one working example:

Example:

Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:

Step Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org.
4 Create Java classes TextEditorConfig, TextEditor, SpellChecker and MainApp under the com.tutorialspoint package.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

Here is the content of TextEditorConfig.java file:

package com.tutorialspoint;
import org.springframework.context.annotation.*; @Configuration
public class TextEditorConfig { @Bean
public TextEditor textEditor(){
return new TextEditor( spellChecker() );
} @Bean
public SpellChecker spellChecker(){
return new SpellChecker( );
}
}

Here is the content of TextEditor.java file:

package com.tutorialspoint;

public class TextEditor {
private SpellChecker spellChecker; public TextEditor(SpellChecker spellChecker){
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}

Following is the content of another dependent class file SpellChecker.java:

package com.tutorialspoint;

public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
} public void checkSpelling(){
System.out.println("Inside checkSpelling." );
} }

Following is the content of the MainApp.java file:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*; public class MainApp {
public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(TextEditorConfig.class); TextEditor te = ctx.getBean(TextEditor.class); te.spellCheck();
}
}

Once you are done with creating all the source filesand adding required additional libraries, let us run the application. You should note that there is no configuration file required. If everything is fine with your application, this will print the following message:

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

The @Import Annotation:

The @Import annotation allows for loading @Bean definitions from another configuration class. Consider a ConfigA class as follows:

@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}

You can import above Bean declaration in another Bean Declaration as follows:

@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B a() {
return new A();
}
}

Now, rather than needing to specify both ConfigA.class and ConfigB.class when instantiating the context, only ConfigB needs to be supplied as follows:

public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(ConfigB.class);
// now both beans A and B will be available...
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}

Lifecycle Callbacks:

The @Bean annotation supports specifying arbitrary initialization and destruction callback methods, much like Spring XML's init-method and destroy-method attributes on the bean element:

public class Foo {
public void init() {
// initialization logic
}
public void cleanup() {
// destruction logic
}
} @Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "cleanup" )
public Foo foo() {
return new Foo();
}
}

Specifying Bean Scope:

The default scope is singleton, but you can override this with the @Scope annotation as follows:

@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public Foo foo() {
return new Foo();
}
}

[转] Spring - Java Based Configuration的更多相关文章

  1. [转载]Spring Java Based Configuration

    @Configuration & @Bean Annotations Annotating a class with the @Configuration indicates that the ...

  2. Spring 3 Java Based Configuration with @Value

    Springsource has released the Javaconfig Framework as a core component of Spring 3.0. There is a tre ...

  3. [转载]Spring Annotation Based Configuration

    Annotation injection is performed before XML injection, thus the latter configuration will override ...

  4. spring Annotation based configuration

    spring 注解相关 https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s11.html

  5. 你真的懂Spring Java Config 吗?Full @Configuration vs lite @Bean mode

    Full @Configuration和lite @Bean mode 是 Spring Java Config 中两个非常有意思的概念. 先来看一下官方文档关于这两者的相关内容: The @Bean ...

  6. Unit Testing of Spring MVC Controllers: Configuration

    Original Link: http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-m ...

  7. Spring 4 Ehcache Configuration Example with @Cacheable Annotation

    http://www.concretepage.com/spring-4/spring-4-ehcache-configuration-example-with-cacheable-annotatio ...

  8. spring java config 初探

    Java Config 注解 spring java config作为同xml配置形式的另一种表达形式,使用的场景越来越多,在新版本的spring boot中 大量使用,今天我们来看下用到的主要注解有 ...

  9. 原创 | 我被面试官给虐懵了,竟然是因为我不懂Spring中的@Configuration

    GitHub 3.7k Star 的Java工程师成神之路 ,不来了解一下吗? GitHub 3.7k Star 的Java工程师成神之路 ,真的不来了解一下吗? GitHub 3.7k Star 的 ...

随机推荐

  1. Styles and Themens(5)样式文件Style.xml中各元素的含义

    Style Resource See also Styles and Themes A style resource defines the format and look for a UI. A s ...

  2. [Hadoop源码解读](一)MapReduce篇之InputFormat

    平时我们写MapReduce程序的时候,在设置输入格式的时候,总会调用形如job.setInputFormatClass(KeyValueTextInputFormat.class);来保证输入文件按 ...

  3. BZOJ3166: [Heoi2013]Alo

    3166: [Heoi2013]Alo Time Limit: 20 Sec  Memory Limit: 256 MBSubmit: 394  Solved: 204[Submit][Status] ...

  4. Maven详解 之 聚合与继承

    说到聚合与继承我们都很熟悉,maven同样也具备这样的设计原则,下面我们来看一下Maven的pom如何进行聚合与继承的配置实现. 一.为什么要聚合? 随着技术的飞速发展和各类用户对软件的要求越来越高, ...

  5. (转)使用pth文件,让python方便的import自己写的模块

    转自:http://www.elias.cn/Python/PythonPath 文章简单易懂,有理有据. 有时候我们正在修改或调试的程序会是一个库,为修改方便,我们可能不大希望把它放到 site-p ...

  6. 【CSS】Intermediate5:Specificity

    1.More Specific=Greater Precedence =>nested selectors 2. the selectors are the same then the last ...

  7. oracle rac 学习(转载)

    一. RAC 并发 RAC 的本质是一个数据库,运行在多台计算机上的数据库,它的主要任务是数据库就是事务处理,它通过 Distributed Lock Management(DLM:分布式锁管理器)  ...

  8. flash挡住了下拉菜单

    遇到了flash挡住了菜单的疑难问题. 在网上查了资料,大部分都说是加一个 <param name="wmode" value="transparent" ...

  9. RTCP

    RTCP RTCP协议将控制包周期发送给所有连接者,应用与数据包相同的分发机制.低层协议提供数据与控制包的复用,如使用单独的UDP端口号.RTCP执行下列四大功能: (1) 主要是提供数据发布的质量反 ...

  10. UEditor 使用过程中问题

    UEditor  百度的文本编辑器   具体详细信息请去百度文本编辑器官网,这里不多说了. 我使用的是 UBuilder 版本的NET版本 ,我只是需要图片上传功能,所以就做了最小化的定制.(可以在官 ...