Spring 基于Java配置

简介:

到目前为止,您已经了解了如何配置使用XML配置文件的Spring bean。如果习惯使用XML配置,那么会说,这不是真的需要学习如何进行基于Java的配置,因为你要使用的配置或者可达到相同的结果。

基于Java配置选项,可以编写大多数的Spring不用配置XML,但有几个基于Java的注释的帮助下解释。

@Configuration & @Bean 注解:

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

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

上面的代码将等同于下面的XML配置:

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

下面注解为@Bean的方法名称作为工作bean的id,它创建并返回实际的bean。配置类可以有声明多个@Bean。一旦配置类定义,可以加载和提供他们使用AnnotationConfigApplicationContext 如下,以Spring容器:

 
public static void main ( String [] args ) {
ApplicationContext ctx = new AnnotationConfigApplicationContext ( HelloWorldConfig . class );
HelloWorld helloWorld = ctx . 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 ();
}

例子:

让我们使用Eclipse IDE,然后按照下面的步骤来创建一个Spring应用程序:

步骤 描述
1 Create a project with a name SpringExample and create a package com.yiibai 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.yiibaipackage.
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.

这里是HelloWorldConfig.java文件的内容:

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

这里是HelloWorld.java的文件的内容:

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

以下是MainApp.java文件的内容:

 
package com . yiibai ;
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 ();
}
}

创建所有的源文件并添加所需的额外(外部)的库,让我们运行应用程序。应该注意,不需要配置文件。如果一切顺利,这将打印以下信息:

 Your Message : Hello World! 

注入Bean的依赖关系:

当@Bean对彼此的依赖,表达这种依赖很简单,只要有一个Bean的方法调用另一个如下:

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

在这里,Bean接收基准通过构造函数注入。现在,让我们看到一个正常工作的例子:

例子:

让我们使用Eclipse IDE,然后按照下面的步骤来创建一个Spring应用程序:

步骤 描述
1 Create a project with a name SpringExample and create a package com.yiibai 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 thecom.yiibai 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.

这里是TextEditorConfig.java文件的内容:

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

这里是TextEditor.java文件的内容:

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

下面是另外一个相关的类文件SpellChecker.java内容:

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

以下是MainApp.java文件的内容:

 
package com . yiibai ;
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 ();
}
}

创建所有的源文件并添加所需的额外的库完成,让我们运行应用程序。应该注意,不需要配置文件。如果一切顺利,这将打印以下信息:

 
Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

@Import 注解:

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

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

您可以在另一个bean声明导入上述bean声明如下:

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

现在,不需要实例化的前提下,当同时指定配置A.class和配置B.class,只有Config B类需要如下提供:

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

生命周期回调:

@Bean注解支持指定任意的初始化和销毁回调方法,就像Spring的XML的初始化方法和bean元素销毁方法的属性:

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

指定Bean的适用范围:

默认范围是单例,但可以使用@Scope注解来覆盖此如下:

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

原文发布时间为:2018-10-25
本文来自云栖社区合作伙伴“ Java杂记”,了解相关信息可以关注“ Java杂记”。
相关文章
|
3天前
|
Java
Java配置环境
Java配置环境
10 0
Java配置环境
|
3天前
|
Java Nacos 开发者
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
Java从入门到精通:4.2.1学习新技术与框架——以Spring Boot和Spring Cloud Alibaba为例
|
3天前
|
Dubbo Java 应用服务中间件
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架
Java从入门到精通:3.2.2分布式与并发编程——了解分布式系统的基本概念,学习使用Dubbo、Spring Cloud等分布式框架
|
7天前
|
存储 安全 Java
第2章 Spring Security 的环境设置与基础配置(2024 最新版)(下)
第2章 Spring Security 的环境设置与基础配置(2024 最新版)(下)
16 0
|
7天前
|
安全 Java 数据库
第2章 Spring Security 的环境设置与基础配置(2024 最新版)(上)
第2章 Spring Security 的环境设置与基础配置(2024 最新版)
33 0
|
8天前
|
安全 Java Spring
Spring Security 5.7 最新配置细节(直接就能用),WebSecurityConfigurerAdapter 已废弃
Spring Security 5.7 最新配置细节(直接就能用),WebSecurityConfigurerAdapter 已废弃
20 0
|
8天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
24 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
9天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
10天前
|
负载均衡 Java 开发者
细解微服务架构实践:如何使用Spring Cloud进行Java微服务治理
【4月更文挑战第17天】Spring Cloud是Java微服务治理的首选框架,整合了Eureka(服务发现)、Ribbon(客户端负载均衡)、Hystrix(熔断器)、Zuul(API网关)和Config Server(配置中心)。通过Eureka实现服务注册与发现,Ribbon提供负载均衡,Hystrix实现熔断保护,Zuul作为API网关,Config Server集中管理配置。理解并运用Spring Cloud进行微服务治理是现代Java开发者的关键技能。
|
11天前
|
安全 Java 数据安全/隐私保护
使用Spring Security进行Java身份验证与授权
【4月更文挑战第16天】Spring Security是Java应用的安全框架,提供认证和授权解决方案。通过添加相关依赖到`pom.xml`,然后配置`SecurityConfig`,如设置用户认证信息和URL访问规则,可以实现应用的安全保护。认证流程包括请求拦截、身份验证、响应生成和访问控制。授权则涉及访问决策管理器,如基于角色的投票。Spring Security为开发者构建安全应用提供了全面且灵活的工具,涵盖OAuth2、CSRF保护等功能。