基于Java的配置

@Configuration & @Bean Annotations

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

  1. package com.tutorialspoint;
  2. import org.springframework.context.annotation.*;
  3. @Configuration
  4. public class HelloWorldConfig {
  5. @Bean
  6. public HelloWorld helloWorld(){
  7. return new HelloWorld();
  8. }
  9. }

它和以下的XML方式定义的是等价的:

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

带@Bean的方法名作为bean id注释,他创建并返回实际的bean。一个配置类可以拥有多个Bean的声明。一旦定义了配置类,你可以通过 AnnotationConfigApplicationContex加载并获取

他们。

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

也可以获取加载不同的configuration

  1. public static void main(String[] args) {
  2. AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
  3. ctx.register(AppConfig.class, OtherConfig.class);
  4. ctx.register(AdditionalConfig.class);
  5. ctx.refresh();
  6. MyService myService = ctx.getBean(MyService.class);
  7. myService.doStuff();
  8. }

Example

HelloWorldConfig.java

  1. @Configuration
  2. public class HelloWorldConfig {
  3. @Bean
  4. public HelloWorld helloWorld(){
  5. return new HelloWorld();
  6. }
  7. }

HelloWorld.java

  1. public class HelloWorld {
  2. private String message;
  3. public void setMessage(String message){
  4. this.message = message;
  5. }
  6. public void getMessage(){
  7. System.out.println("Your Message : " + message);
  8. }
  9. }

MainApp.java

  1. public class MainApp {
  2. public static void main(String[] args) {
  3. ApplicationContext ctx =
  4. new AnnotationConfigApplicationContext(HelloWorldConfig.class);
  5. HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
  6. helloWorld.setMessage("Hello World!");
  7. helloWorld.getMessage();
  8. }
  9. }

输出:

  1. Your Message : Hello World!

注入Bean依赖

当@ bean相互依赖时,表示依赖关系就像让一个bean方法调用另一个bean一样简单,如下所示

  1. @Configuration
  2. public class AppConfig {
  3. @Bean
  4. public Foo foo() {
  5. return new Foo(bar());
  6. }
  7. @Bean
  8. public Bar bar() {
  9. return new Bar();
  10. }
  11. }

foo bean通过构造函数注入接收到bar的引用

Example

TextEditorConfig.java

  1. @Configuration
  2. public class TextEditorConfig {
  3. @Bean
  4. public TextEditor textEditor(){
  5. return new TextEditor( spellChecker() );
  6. }
  7. @Bean
  8. public SpellChecker spellChecker(){
  9. return new SpellChecker( );
  10. }
  11. }

TextEditor.java

  1. public class TextEditor {
  2. private SpellChecker spellChecker;
  3. public TextEditor(SpellChecker spellChecker){
  4. System.out.println("Inside TextEditor constructor." );
  5. this.spellChecker = spellChecker;
  6. }
  7. public void spellCheck(){
  8. spellChecker.checkSpelling();
  9. }
  10. }

SpellChecker.java

  1. public class SpellChecker {
  2. public SpellChecker(){
  3. System.out.println("Inside SpellChecker constructor." );
  4. }
  5. public void checkSpelling(){
  6. System.out.println("Inside checkSpelling." );
  7. }
  8. }

MainApp.java

  1. public class MainApp {
  2. public static void main(String[] args) {
  3. ApplicationContext ctx =
  4. new AnnotationConfigApplicationContext(TextEditorConfig.class);
  5. TextEditor te = ctx.getBean(TextEditor.class);
  6. te.spellCheck();
  7. }
  8. }

输出:

  1. Inside SpellChecker constructor.
  2. Inside TextEditor constructor.
  3. Inside checkSpelling.

@Import注解

@Import注解允许在一个Configuration中导入另外一个配置类。

  1. @Configuration
  2. public class ConfigA {
  3. @Bean
  4. public A a() {
  5. return new A();
  6. }
  7. }
  1. @Configuration
  2. @Import(ConfigA.class)
  3. public class ConfigB {
  4. @Bean
  5. public B a() {
  6. return new A();
  7. }
  8. }

这样,只需要加载ConfigB,则可以加载A,B两个配置文件,而不需要一样加载两次.

Lifecycle Callbacks(声明周期回调)

@bean注释支持指定任意的初始化和销毁回调方法,就像Spring XML的init方法和销毁方法。

  1. public class Foo {
  2. public void init() {
  3. // initialization logic
  4. }
  5. public void cleanup() {
  6. // destruction logic
  7. }
  8. }
  9. @Configuration
  10. public class AppConfig {
  11. @Bean(initMethod = "init", destroyMethod = "cleanup" )
  12. public Foo foo() {
  13. return new Foo();
  14. }
  15. }

指定Bean的作用域

默认作用域是singleton,可以通过以下方法重写:

  1. @Configuration
  2. public class AppConfig {
  3. @Bean
  4. @Scope("prototype")
  5. public Foo foo() {
  6. return new Foo();
  7. }
  8. }

Spring入门学习笔记(2)——基于Java的配置的更多相关文章

  1. Spring入门(8)-基于Java配置而不是XML

    Spring入门(8)-基于Java配置而不是XML 本文介绍如何应用Java配置而不是通过XML配置Spring. 0. 目录 声明一个简单Bean 声明一个复杂Bean 1. 声明一个简单Bean ...

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

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

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

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

  4. Spring入门学习笔记(1)

    目录 Spring好处 依赖注入 面向面编程(AOP) Spring Framework Core Container Web Miscellaneous 编写第一个程序 IoC容器 Spring B ...

  5. [spring入门学习笔记][spring的IoC原理]

    什么叫IoC 控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度.其中最常见的方式叫做依赖注入(Dependency ...

  6. [Spring入门学习笔记][创建网站URL]

    设计网站的URL 现代的Web站点都会设计一套拥有明确意义,方便用户记忆的URL,不论是域名还是路径,以天码营为例: http://tianmaying.com/courses表示网站下所有的课程列表 ...

  7. [Spring入门学习笔记][Spring Boot]

    什么是Spring Boot Spring Boot正是在这样的一个背景下被抽象出来的开发框架,它本身并不提供Spring框架的核心特性以及扩展功能,只是用于快速.敏捷地开发新一代基于Spring框架 ...

  8. [Spring入门学习笔记][静态资源]

    遗留问题 在上一节课的作业中,我们一定遇到了一点问题——虽然将页面内容正确的返回给了浏览器,但是浏览器显示的样式却是不正确的,这是因为在HTML的\标签中我们这样引入了CSS资源: <link ...

  9. [Spring入门学习笔记][Spring的AOP原理]

    AOP是什么? 面向切面编程 软件工程有一个基本原则叫做“关注点分离”(Concern Separation),通俗的理解就是不同的问题交给不同的部分去解决,每部分专注于解决自己的问题.这年头互联网也 ...

随机推荐

  1. ueditor 百度编辑器 解决表格没有边框

    因为项目需要,发现直接从word和excel复制粘贴以后,居然在禅道上表格没有边框了,故查了一下 这里从word,以及excel粘贴复制,都能直接有边框了,同时在编辑器里面新增表格,也能直接显示边框了 ...

  2. 【node.js】Express 框架

    Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具. 使用 Express 可以快速地搭建一个完整功能的网 ...

  3. python 标准库简介

    操作系统接口 os 模块提供了许多与操作系统交互的函数: >>> >>> import os >>> os.getcwd() # Return t ...

  4. R语言爬虫:使用R语言爬取豆瓣电影数据

    豆瓣排名前25电影及评价爬取 url <-'http://movie.douban.com/top250?format=text' # 获取网页原代码,以行的形式存放在web 变量中 web & ...

  5. C++编写DLL动态链接库的步骤与实现方法

    原文:http://www.jb51.net/article/90111.htm 本文实例讲述了C++编写DLL动态链接库的步骤与实现方法.分享给大家供大家参考,具体如下: 在写C++程序时,时常需要 ...

  6. stat命令的实现-mysate 20155239吕宇轩

    stat命令的实现-mysate 20155239吕宇轩 学习使用stat(1),并用C语言实现 提交学习stat(1)的截图 man -k ,grep -r的使用 伪代码 产品代码 mystate. ...

  7. vab set dim

    '问题一'给普通变量赋值使用LET ,只是LET 可以省略.'给对象变量赋值使用SET,SET 不能省略. Sub AA()    Dim arr As String    arr = "h ...

  8. JavaWeb总结(二)

    Web服务器的缺陷 Web服务器是被设计用来向客户端提供HTTP服务的,它只能向客户端提供静态网页内容.静态页面是原封不动的待在Web服务器目录中,服务器找到静态网页,并把它原样传回到客户端.每个客户 ...

  9. PostgreSQL的PITR中,对 unfilled wal log 如何处理为好

    磨砺技术珠矶,践行数据之道,追求卓越价值 回到上一级页面: PostgreSQL基础知识与基本操作索引页     回到顶级页面:PostgreSQL索引页 通过实验,可以发现,PostgreSQL中使 ...

  10. 5290: [Hnoi2018]道路

    5290: [Hnoi2018]道路 链接 分析: 注意题目中说每个城市翻新一条连向它的公路或者铁路,所以两种情况分别转移一下即可. 注意压一下空间,最后的叶子节点不要要访问,空间少了一半. 代码: ...