一般常用的装配第三方组件有两种方式:1、通过spi 2、通过注解
通过spi
看下自己自定义的项目结构 :
注意:这个项目只需要引入spring的依赖,不需要引入springboot的依赖,当然引入springboot依赖也是可以的
如pom.xml
4.0.0 org.example springboot_spi1.0-SNAPSHOT org.springframework spring-core4.3.7.RELEASE org.springframework spring-beans4.3.7.RELEASE org.springframework spring-context4.3.7.RELEASE
springboot 在项目启动的时候会自动去扫描 classpath下meta-INF下的spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.fen.dou.TestAutoConfig
通过org.springframework.boot.autoconfigure.EnableAutoConfiguration作为key,去获取需要注入的类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestAutoConfig {
@Bean
public SayHello sayHello(){
return new SayHello();
}
}
注意:自动装配的类一定要用@Configuration注解进行修饰,并用@bean声明需要注入的bean,用@Component是不行的
public class SayHello {
public void say(){
System.out.println("-----------------hello--------------------");
}
}
然后在其他的项目中用maven进行引入,在没有maven私有仓库的情况下,可以把这两个项目弄成两个module
在另外一个module中引入:
org.example springboot_spi1.0-SNAPSHOT
看已经装配进去了
通过注解
先来创建一个module
pom.xml:
4.0.0 org.example springboot_annotation1.0-SNAPSHOT org.springframework spring-core4.3.7.RELEASE org.springframework spring-beans4.3.7.RELEASE org.springframework spring-context4.3.7.RELEASE
public class SayWelcome {
public void say(){
System.out.println("-----------------welcome--------------------");
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestAnnotationAutoConfig {
@Bean
public SayWelcome sayWelcome(){
return new SayWelcome();
}
}
在另外一个module中引入:
org.example springboot_annotation1.0-SNAPSHOT
在另外一个项目创建注解:EnableAutoConfigurationCustom,这里使用了import注解把那个配置类注入进去
import com.fen.dou.TestAnnotationAutoConfig;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.context.annotation.import;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@documented
@Inherited
@AutoConfigurationPackage
@import(TestAnnotationAutoConfig.class)
public @interface EnableAutoConfigurationCustom {
}
并且在启动类引入这个注解:
运行如下:



