以下内容引用自http://wiki.jikexueyuan.com/project/spring/java-based-configuration.html

基于Java的配置选项,可以使你在不用配置XML的情况下编写大多数的Spring配置。

@Configuration和@Bean注解

带有@Configuration的注解类表示这个类可以使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。最简单可行的@Configuration类如下所示:

@Configuration
public class HelloWorldConfig { @Bean
public HelloWorld helloWorld(){
return new HelloWorld();
} }

对应XML配置如下:

<beans>
<bean id="helloWorld" class="com.jsoft.testspring.testjavaconfiguration.HelloWorld" />
</beans>

在这里,带有@Bean注解的方法名称作为bean的ID,它创建并返回实际的bean。你的配置类可以声明多个@Bean。一旦定义了配置类,你就可以使用AnnotationConfigApplicationContext来加载并把他们提供给Spring容器,如下所示:

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

}

当然,你可以加载各种配置类,如下所示:

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();

}

例子:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.jsoft.testspring</groupId>
<artifactId>testjavaconfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>testjavaconfiguration</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

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

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

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

App.java:

package com.jsoft.testspring.testjavaconfiguration;

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

}
}

测试结果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test13/testjavaconfiguration

Bean的依赖性注入

当Beans依赖对方时,表达这种依赖性非常简单,只要有一个bean方法调用另一个,如下所示:

@Configuration
public class HelloWorldConfig { @Bean
public HelloWorld helloWorld(){
return new HelloWorld(message());
} @Bean
public String message(){
return new String("Hello World"
);
}
}

可以看出,有依赖性时直接在类中调用新建的方法即可。

例子:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.jsoft.testspring</groupId>
<artifactId>testjavaconfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>testjavaconfiguration</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
private String message; public HelloWorld(String message){
this.message = message;
} public void getMessage(){
System.out.println(this.message);
}
}

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class HelloWorldConfig { @Bean
public HelloWorld helloWorld(){
return new HelloWorld(message());
} @Bean
public String message(){
return new String("Hello World"
);
}
}

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);

helloWorld.getMessage();

}
}

测试结果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test13/testjavaconfiguration1

@Import注释

@import注解允许从另一个配置类中加载Bean定义。如下所示:

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

现在,当实例化上下文时,不需要同时指定ConfigA.class和ConfigB.class,只要ConfigB类需要提供,如下所示:

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class); A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}

例子:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.jsoft.testspring</groupId>
<artifactId>testjavaconfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>testjavaconfiguration</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
private String message; public HelloWorld(String message){
this.message = message;
} public void getMessage(){
System.out.println(this.message);
}
}

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class HelloWorldConfig { @Bean
public HelloWorld helloWorld(){
return new HelloWorld(message());
} @Bean
public String message(){
return new String("Hello World"
);
}
}

HelloWorldConfigB.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; @Configuration
@Import(HelloWorldConfig.class)
public class HelloWorldConfigB { @Bean
public String messageB(){
return new String("Hello B");
}
}

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfigB.class);
HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);

helloWorld.getMessage();

}
}

可以看出不用再次引用HelloWorldConfig.java类了。

测试结果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test13/testjavaconfiguration2

生命周期回调

@Bean注解支持指定任意的初始化和销毁​​回调方法,这与Spring元素中的Spring XML的init-method和destroy-method属性非常相似。如下所示:

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

例子:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.jsoft.testspring</groupId>
<artifactId>testjavaconfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>testjavaconfiguration</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
private String message; public HelloWorld(String message){
this.message = message;
} public void getMessage(){
System.out.println(this.message);
} public void init(){
System.out.println("HelloWorld init");
} public void cleanup(){
System.out.println("HelloWorld cleanup"
);
}

}

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class HelloWorldConfig { @Bean(initMethod="init",destroyMethod="cleanup")
public HelloWorld helloWorld(){
return new HelloWorld(message());
} @Bean
public String message(){
return new String("Hello World");
} }

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext; /**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
helloWorld.getMessage();
applicationContext.registerShutdownHook();
}
}

测试结果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test13/testjavaconfiguration3

指定Bean的作用域范围

默认范围是单实例,但是你可以重写带有@Scope注解的方法,如下所示:

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

例子:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.jsoft.testspring</groupId>
<artifactId>testjavaconfiguration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>testjavaconfiguration</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

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

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; @Configuration
public class HelloWorldConfig { @Bean
@Scope("prototype")
public HelloWorld helloWorld(){
return new HelloWorld();
} }

@Scope的值和xml中配置的保持一致。

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; /**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World 1!");
helloWorld.getMessage();
HelloWorld helloWorld2 = applicationContext.getBean(HelloWorld.class
);
helloWorld2.getMessage();

}
}

测试结果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test13/testjavaconfiguration4

更多Java配置的官方例子参考:https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

Spring基于Java的配置的更多相关文章

  1. Spring 基于 Java 的配置

    前面已经学习如何使用 XML 配置文件来配置 Spring bean. 基于 Java 的配置可以达到基于XML配置的相同效果. 基于 Java 的配置选项,可以使你在不用配置 XML 的情况下编写大 ...

  2. Spring学习笔记--使用Spring基于Java的配置

    我们需要使用@Component注解来定义一个配置类,在配置类中我们定义Bean: package com.moonlit.myspring; import org.springframework.c ...

  3. Spring IOC之基于JAVA的配置

    基础内容:@Bean 和 @Configuration 在Spring中新的支持java配置的核心组件是 @Configuration注解的类和@Bean注解的方法. @Bean注解被用于表明一个方法 ...

  4. Spring入门学习笔记(2)——基于Java的配置

    目录 基于Java的配置 @Configuration & @Bean Annotations Example 注入Bean依赖 @Import注解 Lifecycle Callbacks(声 ...

  5. Spring框架入门之基于Java注解配置bean

    Spring框架入门之基于Java注解配置bean 一.Spring bean配置常用的注解 常用的有四个注解 Controller: 用于控制器的注解 Service : 用于service的注解 ...

  6. Spring 基于注解零配置开发

    本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址:< Spring 基于注解零配置开发 > 一:搜索Bean 再也不用在XML文件里写什么配置信息了. Sprin ...

  7. Spring 基于Java的Bean声明

    Spring 基于Java的Bean声明 使用@Configuration进行设置: Xml: <?xml version="1.0" encoding="UTF- ...

  8. (4.1)Spring MVC执行原理和基于Java的配置过程

    一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...

  9. Spring MVC执行原理和基于Java的配置过程

    一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...

随机推荐

  1. MongoDB最简单的入门教程之二 使用nodejs访问MongoDB

    在前一篇教程 MongoDB最简单的入门教程之一 环境搭建 里,我们已经完成了MongoDB的环境搭建. 在localhost:27017的服务器上,在数据库admin下面创建了一个名为person的 ...

  2. Java面试题之HashSet 的实现原理?

    HashSet 的实现原理?首先,我们需要知道它是Set的一个实现,所以保证了当中没有重复的元素.一方面Set中最重要的一个操作就是查找.而且通常我们会选择 HashSet来实现,因为它专门对快速查找 ...

  3. Python3基础教程(十五)—— PEP8 代码风格指南

    编程语言不是艺术,而是工作或者说是工具,所以整理并遵循一套编码规范是十分必要的. 这篇文章原文实际上来自于这里:https://www.python.org/dev/peps/pep-0008/ 有很 ...

  4. uva1609 Foul Play

    思维 创造条件使一轮比赛之后仍满足1号打败至少一半,并剩下至少一个t' 紫书上的思路很清晰阶段1,3保证黑色至少消灭1半 #include<cstdio> #include<vect ...

  5. 这就是那个feature map256 256向量

    http://blog.csdn.net/XZZPPP/article/details/51582810 在这个特征图上使用3*3的卷积核(滑动窗口)与特征图进行卷积,那么这个3*3的区域卷积后可以获 ...

  6. OpenCV:应用篇

    手势跟踪识别 车牌检测 人脸识别 去雾 图像阈值分割提取

  7. _vimrc配置

    set nocompatible set encoding=utf8 set guioptions-=T set number set guifont=consolas:h12 source $VIM ...

  8. xcode中自定义log打印

    打印内容包括 在哪个文件中 ? 在哪个方法中? 将要执行什么操作?   // 此打印实现前提: // 1.在.pch文件中实现自定义log打印方法,log名换为LCLog // 2.定义一个宏obje ...

  9. SqlSugar直接执行Sql

    参考:http://www.codeisbug.com/Doc/8/1132 我的思路: 1.数据库中写好sql 2.用SqlSugar直接执行sql,获取DataTable的数据 3.DataTab ...

  10. 调试bug方法总结

    打印法 debugger 分段屏蔽法 有没有涉及到异步.延迟请求 渲染顺序