Spring 基于 Java 的配置

转载自  Spring 基于 Java 的配置

基于 Java 的配置

到目前为止,你已经看到如何使用 XML 配置文件来配置 Spring bean。如果你熟悉使用 XML 配置,那么我会说,不需要再学习如何进行基于 Java 的配置是,因为你要达到相同的结果,可以使用其他可用的配置。

基于 Java 的配置选项,可以使你在不用配置 XML 的情况下编写大多数的 Spring,但是一些有帮助的基于 Java 的注解,解释如下:

@Configuration 和 @Bean 注解

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

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

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

<beans><bean id="helloWorld" class="com.tutorialspoint.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创建一个名称为 SpringExample 的项目,并且在创建项目的 src 文件夹中创建一个包 com.tutorialspoint
2使用 Add External JARs 选项,添加所需的 Spring 库,解释见 Spring Hello World Example 章节。
3因为你是使用基于 java 的注解,所以你还需要添加来自 Java 安装目录的 CGLIB.jar 和可以从 asm.ow2.org 中下载的 ASM.jar 库。
4在 com.tutorialspoint 包中创建 Java 类 HelloWorldConfigHelloWorld和 MainApp
5最后一步是创建的所有 Java 文件和 Bean 配置文件的内容,并运行应用程序,解释如下所示。

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

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

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

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

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

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

一旦你完成了创建所有的源文件并添加所需的额外的库后,我们就可以运行该应用程序。你应该注意这里不需要配置文件。如果你的应用程序一切都正常,将输出以下信息:

Your Message : Hello World!

注入 Bean 的依赖性

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

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

这里,foo Bean 通过构造函数注入来接收参考基准。现在,让我们看到一个正在执行的例子:

例子:

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

步骤描述
1创建一个名称为 SpringExample 的项目,并且在创建项目的 src 文件夹中创建一个包 com.tutorialspoint
2使用 Add External JARs 选项,添加所需的 Spring 库,解释见 Spring Hello World Example 章节。
3因为你是使用基于 java 的注解,所以你还需要添加来自 Java 安装目录的 CGLIB.jar 和可以从 asm.ow2.org 中下载的 ASM.jar 库。
4在 com.tutorialspoint 包中创建 Java 类 TextEditorConfigTextEditorSpellChecker 和 MainApp
5最后一步是创建的所有 Java 文件和 Bean 配置文件的内容,并运行应用程序,解释如下所示。

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

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

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

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

下面是另一个依赖的类文件 SpellChecker.java 的内容:

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

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

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

一旦你完成了创建所有的源文件并添加所需的额外的库后,我们就可以运行该应用程序。你应该注意这里不需要配置文件。如果你的应用程序一切都正常,将输出以下信息:

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

@Import 注解:

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

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

你可以在另一个 Bean 声明中导入上述 Bean 声明,如下所示:

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

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

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 注解支持指定任意的初始化和销毁的回调方法,就像在 bean 元素中 Spring 的 XML 的初始化方法和销毁方法的属性:

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/326623.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2016蓝桥杯省赛---java---B---3(凑算式)

题目描述 凑算式 思路分析 通分 代码实现 package com.atguigu.TEST;class Main{static int a[]{1,2,3,4,5,6,7,8,9};static int ans;public static boolean check(){int xa[3]*100a[4]*10a[5];int ya[6]*100a[7]*10a[8];if((a[1]*ya[2]*x)%(y*a[2])0&&a[0](a[1…

java如何连接mysql_Java如何连接数据库

Java如何连接数据库1.加载驱动Class.forname(ClassName);2.建立数据库连接使用DriverManager类的getConnection()静态方法来获取数据库连接对象&#xff0c;其语法格式如下所示:Connection connDriverManager.getConnection(String url,String userName,String password);其中u…

Spring 基于注解的配置

转载自 Spring 基于注解的配置 基于注解的配置 从 Spring 2.5 开始就可以使用注解来配置依赖注入。而不是采用 XML 来描述一个 bean 连线&#xff0c;你可以使用相关类&#xff0c;方法或字段声明的注解&#xff0c;将 bean 配置移动到组件类本身。 在 XML 注入之前进行注解…

微软.NET年芳15:我在Azure上搭建Photon服务器(C#.NET)

摘录网上的“.NET 15周年”信息如下&#xff1a; 微软的 .NET 框架本周迎来了 15 岁生日。.NET 的第一个版本在 2002 年 2 月 13 日作为的 Visual Studio.NET 的一部分首次公开亮相。过去 15 年&#xff0c;.NET 框架从一个流行的闭源软件开发平台&#xff0c;变成了一个开源的…

分治算法---汉诺塔

思路分析 代码实现 package com.atguigu.dac;public class Hanoitower {public static void main(String[] args) {hanoiTower(5,A,B,C);}//汉诺塔移动的方法//使用分治算法public static void hanoiTower(int num,char a,char b,char c){//如果只有一个盘if(num1){System.out…

数组复习

在我周围&#xff0c;像我这种性格的人特多——在公众场合什么都不说&#xff0c;到了私下里却妙语连珠&#xff0c;换言之&#xff0c;对信得过的人什么都说&#xff0c;对信不过的人什么都不说。保持沉默是怯懦的。——《沉默的大多数》ssh整合案例1泪点伊人颜多少红尘过客&a…

mysql id生成器自定义_MybatisPlus使用自定义Id生成器数据自动填充

使用自定义ID生成器实现IdentifierGenerator接口Componentpublic class CustomerIdGenerator implements IdentifierGenerator {Overridepublic Number nextId(Object entity) {// 填充自己的Id生成器&#xff0c;return HolaSms.snowFlake();}}实体类或者配置文件中指定id填充…

Spring JSR-250 注释

转载自 Spring JSR-250 注释 Spring JSR-250 注释 Spring还使用基于 JSR-250 注释&#xff0c;它包括 PostConstruct&#xff0c; PreDestroy 和 Resource 注释。因为你已经有了其他的选择&#xff0c;尽管这些注释并不是真正所需要的&#xff0c;但是关于它们仍然让我给出一…

.NET Core跨平台:使用.NET Core开发一个初心源商城总括

1..NET Core基本介绍 a 作为一个.NET的开发者&#xff0c;在以前的开发中&#xff0c;我们开发的项目基本都是部署在windows服务器上,但是在windows服务器上的话某些比较流行的解决访问量的方案基本都是先出现在linux上&#xff0c;而后才能迁移出现windows上&#xff0c;而且效…

二分查找非递归方式实现

思路分析 代码实现 package com.atguigu.binarysearchnorecursion;/*** 创建人 wdl* 创建时间 2021/4/2* 描述*/ public class BinarySearchNoRecur {public static void main(String[] args) {//测试int[] arr{1,3,8,10,11,67,89};int i binarySearch(arr,67);System.out.pr…

jQuery实现判断li的个数从而实现其他功能

需求&#xff1a;当ul中的li大于6个的时候显示图片&#xff0c;当li小于6个的时候隐藏图片&#xff0c;先来看看效果&#xff1a; 当有7个li的时候&#xff1a; 当有3个li的时候&#xff1a; 现在吧源码放上来&#xff1a; <!DOCTYPE html> <html><head…

windows mysql memcached_Memcached在Windows下的安装

前言 &#xff1a; 简介下 Memcached 和 Memcache 的区别和联系Memcached和Memcache的区别&#xff0c;其实很简单&#xff0c;一个是服务端&#xff0c;一个是客户端&#xff0c;就像mysql一样&#xff0c;我们在命令行里输入各种sql语句就能查询到需要的结果&#xff0c;这就…

baiduTemplate / artTemplate

转载自 baiduTemplate / artTemplate JS引擎模板 一、baiduTeplate 模板语法 提供一套模板语法&#xff0c;用户可以定义一个模板区块&#xff0c;每次根据传入的数据生成对应数据产生的html片段&#xff0c;从而渲染不同的界面效果&#xff1b; 优点&#xff1a; 语法简单…

辅助Visual Studio 2017部署的DevOps新工具

我们能看到Visual Studio 2017中的一个重大改进是对安装程序做了完全重写。前期的Visual Studio构建版本都是大一统的&#xff0c;完成安装需要相当长的时间和大量的磁盘空间。因此有需求要对安装过程做一些改进&#xff0c;这在本质上需要改进Visual Studio及其组件的检测方式…

2016蓝桥杯省赛---java---B---6(方格填数)

题目描述 方格填数 思路分析 全排列检查 代码实现 package com.atguigu.TEST;import static java.lang.Math.abs;class Main{static int a[]{0,1,2,3,4,5,6,7,8,9};static int ans;public static boolean check(){if (abs(a[0] - a[1]) 1 || abs(a[0] - a[3]) 1 || abs…

mybatis+spring报错PropertyAccessException 1: org.springframework.beans.MethodInvocationException

报错如下&#xff1a; * org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘dataSource’ defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework…

java中的tostring_java 中重写toString()方法

toString()方法 一般出现在System.out.println(类名.toString());toString()是一种自我描述方法 本身返回的是 getClass().getName() "" Integer.toHexString(hashCode());也就是 类名 hashCode的值重写toString() 只会对类生效&#xff0c;并不能字符串生效; 例如…

art-template入门(一)之介绍

转载自 art-template介绍 介绍 art-template 是一个简约、超快的模板引擎。 它采用作用域预声明的技术来优化模板渲染速度&#xff0c;从而获得接近 JavaScript 极限的运行性能&#xff0c;并且同时支持 NodeJS 和浏览器。在线速度测试。 特性 拥有接近 JavaScript 渲染极…

走过20年……你出现在哪里?

Visual Studio Live 倒计时ing 20岁的 Visual Studio 陪伴了一代代程序猿的成长&#xff0c;从青葱岁月一直走过而立之年&#xff0c;从一个小后生变成了 wuli欧巴……由单身狗也成了孩子他爸…… 如今二十载已过&#xff0c;你还记得当年大明湖畔的 Visual Studio 么&#xff…

2016蓝桥杯省赛---java---B---7(剪邮票)

题目描述 剪邮票 思路分析 全排列深度优先搜索连通检查 代码实现 package com.atguigu.TEST;class Main{static int a[] { 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 };static int ans;static boolean vis[]new boolean[12];static void dfs(int g[][], int i, int j) {g[i][…