15.1 Importing additional configuration classes

你不需要将所有的@Configuration放进一个单独的类,@Import注解可以用来导入其他配置类。另外,你也可以使用@ComponentScan注解自动收集所有Spring组件,包括@Configuration类。

@Configuration注解的类里面都是含有带有@Bean注解的方法,这些配置类相当于声明了bean的xml,添加@Configuration的目的主要是为了能被@ComponentScan自动扫描到

@Configuration注解也不是真的需要,如果你在调用SpringApplication.run()的时候向sources参数明确地传入了配置类,那么就不需要在配置类上添加该注解,但是如果你在Main类(或者其他普通的类,如果没添加basePackage就只自动扫描该类所在包下的被注解的组件)中使用@ComponentScan去自动发现配置类而不传入sources参数给SpringApplication.run(),那么你就需要给这些配置类添加@Configuration

Application.java

package spring.learn.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import spring.learn.springboot.bean.Car;

public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(PrimeConfig.class, args);
        ctx.getBean(Car.class).drive();

    }
}

PrimeConfig.java

package spring.learn.springboot;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class PrimeConfig {

}

Car.java

package spring.learn.springboot.bean;

import org.springframework.stereotype.Component;

@Component
public class Car {
    public void drive() {
        System.out.println("run");
    }
}

@Import@ImportResource的用法

@Import的用法

在使用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-2.5.xsd">

   <import resource="config/customer.xml"/>
   <import resource="config/scheduler.xml"/>

</beans>

那么对应的,Spring-Boot使用@Import(该注解在Spring3中就有了)方式:

package com.mkyong.config;

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

@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {

}

@ImportResource的用法


@Configuration
@Import(CDPlayerConfig.class)  
@ImportResource("classpath:cons-injec.xml") //导入xml配置项
public class SoundSystemConfig {

}

results matching ""

    No results matching ""