Spring JavaConfig

  以前,Spring推荐使用XML的方式来定义Bean及Bean之间的装配规则,但是在Spring3.0之后,Spring提出的强大的JavaConfig这种类型安全的Bean装配方式,它基于Java代码的灵活性,使得装配的过程也变得及其灵活。

@Configuration注解

  我们在定义JavaConfig类时,都会在其上加注@Configuration注解,来表明这是一个配置类,@Configuration注解底层是@Component注解,而且这个注解会被AnnotationConfigApplicationContext来进行加载,AnnotationConfigApplicationContext是ApplicationContext的一个具体实现,代表依据配置注解启动应用上下文。

@ComponentScan注解

  我们使用JavaConfig的目的是为了实现以前XML配置实现的功能,首先就是组件扫描功能,将我们使用特定注解标注的类统一扫描加载到Spring容器,这一功能就是依靠@ComponentScan注解来实现的,我们可以为其指定位置参数来指定要扫描的包。

@Bean注解

  使用@Bean注解我们可以实现XML配置中手动配置第三方Bean的功能,这里我们使用方法来定义Bean,并在方法前面加注@Bean注解,表示要将该方法返回的对象加载到Spring容器中,这样就对我们的方法定义带来了一些限制,这些限制包括方法的大概格式:

  1-方法带返回值,且返回类型为你要加载的第三方类类型

  2-方法的名称为默认的Bean的name,如果要自定义Bean的name,可以使用@Bean注解的name属性。

  3-要实现注入只需要将要注入的Bean的类型作为参数,调用该类的带参数的构造器构建这个Bean,或者采用第二种方式:先创建这个类的对象,然后调用该对象的set方法进行注入,以被注入的Bean的方法为参数

JavaConfig能够等价看成是XML文件,不过它只是用Java编写的。它的完整文档在网上可以看到,而这篇文章帮助你开始使用JavaConfig。让我们把下面的XML文件移植为一个JavaConfig来作为一个例子吧:
<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>
下面是等价的文件: 
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;

@Configuration
public class AppConfig {
    
    @Bean(name="helloBean")
    public HelloWorld helloWorld() {
        return new HelloWorldImpl();
    }
    
}
a.一个简单的bean
package com.spring;

public interface Helloeorld {

    void printHelloWorld(String msg);
}

package com.spring;

public class HelloworldImpl implements Helloeorld{

    @Override
    public void printHelloWorld(String msg) {

        System.out.println("Hello : " + msg);
    }

}

b.javaConfig注解:使用 @Configuration 注释告诉 Spring,这是核心的 Spring 配置文件,并通过 @Bean 定义 bean

package com.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*使用 @Configuration 注释告诉 Spring,这是核心的 Spring 配置文件,
并通过 @Bean 定义 bean*/
@Configuration
public class TestConfig {

    @Bean(name="helloeorld")
    public Helloeorld getHello(){
        return new HelloworldImpl();
        
    }
}

c.测试main方法:
package com.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestMain {
  public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
    Helloeorld obj = (Helloeorld) context.getBean("helloeorld");
    obj.printHelloWorld("Spring Java Config");
  } }
原文地址:https://www.cnblogs.com/yingsong/p/9239913.html