第一个Spring JavaConfig注解配置bean

来源:互联网 发布:linux acl chown 区别 编辑:程序博客网 时间:2024/06/05 10:37

1.如何对bean进行装配,Spring提供了三种主要装配机制:

  • 列表内容在xml中进行显示配置
  • 在Java中进行显示配置
  • 隐式的bean发现机制和自动装配
  1. Spring 3.0引入了Javaconfig配置bean,得到了广大程序员的青睐,因此我们需要重点学习JavaCofig配置,要不然就out了 。

3.JavaConfig是xml一种替代解决方案

package com.yiibai.hello;public interface HelloWorld {    void printHelloWorld(String msg);}package com.yiibai.hello.impl;import com.yiibai.hello.HelloWorld;public class HelloWorldImpl implements HelloWorld {    @Override    public void printHelloWorld(String msg) {        System.out.println("Hello : " + msg);    }}package com.yiibai.core;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import com.yiibai.config.AppConfig;import com.yiibai.hello.HelloWorld;public class App {    public static void main(String[] args) {            ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);        HelloWorld obj = (HelloWorld) context.getBean("helloBean");        obj.printHelloWorld("Spring Java Config");    }}1.使用 AnnotationConfigApplicationContext 加载您的JavaConfig类2.输出结果:Hello : Spring Java Config/////////////////////////////////////////////////////////////////@xml配置<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    <bean id="helloBean" class="com.yiibai.hello.impl.HelloWorldImpl"></beans>/////////////////////////////////////////////////////////////////@2 JavaConfig配置替代以上xml配置package com.yiibai.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.yiibai.hello.HelloWorld;import com.yiibai.hello.impl.HelloWorldImpl;@Configurationpublic class AppConfig {    @Bean(name="helloBean")    public HelloWorld helloWorld() {        return new HelloWorldImpl();    }}

总结:
1.在这里我们使用一个带注解的AppConfig 类代替application.xml文件。
2.@Configuration注解表明该类是一个配置类,该类应该包括在Spring应用上下文中如何创建bean的细节。
3.@Bean注解会告诉Spring这个方法将会返回一个对象,该对象要注册为Spring应用上下问中的bean,方法体中包括最终产生bean实例的逻辑。

原创粉丝点击