Spring基于Java的配置
以下内容引用自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的配置的更多相关文章
- Spring 基于 Java 的配置
前面已经学习如何使用 XML 配置文件来配置 Spring bean. 基于 Java 的配置可以达到基于XML配置的相同效果. 基于 Java 的配置选项,可以使你在不用配置 XML 的情况下编写大 ...
- Spring学习笔记--使用Spring基于Java的配置
我们需要使用@Component注解来定义一个配置类,在配置类中我们定义Bean: package com.moonlit.myspring; import org.springframework.c ...
- Spring IOC之基于JAVA的配置
基础内容:@Bean 和 @Configuration 在Spring中新的支持java配置的核心组件是 @Configuration注解的类和@Bean注解的方法. @Bean注解被用于表明一个方法 ...
- Spring入门学习笔记(2)——基于Java的配置
目录 基于Java的配置 @Configuration & @Bean Annotations Example 注入Bean依赖 @Import注解 Lifecycle Callbacks(声 ...
- Spring框架入门之基于Java注解配置bean
Spring框架入门之基于Java注解配置bean 一.Spring bean配置常用的注解 常用的有四个注解 Controller: 用于控制器的注解 Service : 用于service的注解 ...
- Spring 基于注解零配置开发
本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址:< Spring 基于注解零配置开发 > 一:搜索Bean 再也不用在XML文件里写什么配置信息了. Sprin ...
- Spring 基于Java的Bean声明
Spring 基于Java的Bean声明 使用@Configuration进行设置: Xml: <?xml version="1.0" encoding="UTF- ...
- (4.1)Spring MVC执行原理和基于Java的配置过程
一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...
- Spring MVC执行原理和基于Java的配置过程
一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...
随机推荐
- C++_pthread read-write lock_读写锁_visual studio 2015下配置
pthread下载地址:https://sourceware.org/pthreads-win32/ 1. 项目->属性->VC++目录 包含目录里添加:pthread所在路径\pthre ...
- yii 和 zend studio 集成
yii是基于测试驱动的,而zend studio是一个好用的ide.集成就是必须的. 本文适合喜欢使用ide的开发者,vim用户或者文本编辑器使用者请忽略. 本文使用的是最新的zend studio ...
- Hibernate初始化环境的基本封装
public class HibernateUtils { private static SessionFactory sf; static{ sf = new Configuration().con ...
- zabbix auto registration
1./etc/zabbix/zabbix_agent.conf serverActive=zabbix server ip 2.frontend configuration>actions> ...
- java内存模型(线程共享部分)
1.元空间(MetaSpace)与永久代(PermGen)的区别? ----> 1.1 元空间使用的是本机内存(这样的好处是,可以使用的内存空间变大了,没有OutOfMemoryError:Pe ...
- C和C++中动态链接库的创建和链接(原创,装载请注明原处)
C和C++中动态链接库的创建和链接 1.创建DLL(动态链接库)-C++方式 1.创建DLL(动态链接库-C++方式) 1.在VS(以VS2017为例)中创建DLL动态链接库. 解决方案名称为:MyD ...
- AT2663 Namori Grundy
题目描述: luogu 题解: 好多细节,比如说每个点有且仅有一条入边. 所以说这个图一定是一个基环外向树. 考虑只是一个环的情况,我们可以发现,当环长为偶数时我们可以$01$交替染色,但环长为奇数时 ...
- Jenkins出现 {"changed": false, "msg": "mkdir: cannot create directory ‘/root/.ansible/tmp/ansible-tmp-1552390265.8-253945919613076’: No space left on device\n", "unreachable": true}
之前部署Jenkins没有遇到过这个问题,百度也找不到相关内容,无奈用过google翻译了一下,显示内存不足,上到服务器查询df -h 发现use% 100% 由于日志等文件导致服务器磁盘空间满了,引 ...
- django--基础操作
Django基础操作 django常用命令 创建django项目 django-admin startproject mysite 创建项目完成以后,文件目录结构为: 修改settings文件内容 A ...
- 如何在Python中显式释放内存?
根据Python官方文档,您可以强制垃圾收集器释放未引用的内存gc.collect().例: import gc gc.collect() 所属网站分类: python高级 > 综合&其 ...