2017-09-29 42 views
0

Hy guys!什么是Spring中的JavaConfig?

我只是尝试TU明白其中的含义和注释@Bean的用法,我遇到所谓JavaConfingin this文件(2.2.1章节)这个词。上下文是如下:“要声明一个bean,只需注释与@Bean注释的方法时JavaConfig遇到这样的方法,将执行该方法,并注册(......)”

我不明白是什么JavaConfig是Spring ... 它究竟有什么作用? 当它运行? 为什么运行?

我看到this documentation为好,但并没有使我更接近理解....

感谢您的帮助!

+0

春天核心参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/ – Ivan

回答

5

它引用基于注释的配置,而不是基于旧的原始XML的配置。

实际的JavaConfig组件是通过类文件和注释来构建配置(而不是通过XML文件来构建配置)的组件。

+0

好,很明显,谢谢! – HowToTellForAChild

2

使用@Configuration注解类表明该类可以被Spring IoC容器用作bean定义的源。 @Bean注解(你问到的)告诉Spring,用@Bean注解的方法将返回一个应该在Spring应用程序上下文中注册为bean的对象。最简单的可能@Configuration类将是如下 -

package com.test; 
import org.springframework.context.annotation.*; 

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

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

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

这里,方法的名称标注有@Bean工作豆ID并创建并返回实际的bean。您的配置类可以拥有多个@Bean的声明。一旦你的配置类的定义,您可以加载并为他们提供Spring容器使用AnnotationConfigApplicationContext如下 -

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

例子:

这里是HelloWorldConfig.java文件的内容

package com.test; 
import org.springframework.context.annotation.*; 

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

这里是HelloWorld.java的内容文件

package com.test; 

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.test; 

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!