1.引入依赖

	<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>
        <!--输入properties或yml会自动提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
    </dependencies>

2.写一个TestBean,装载信息

/**
 * 写一个TestBean,装载信息
 */
public class TestBean {

    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

3.写一个Properties类

该类上面的注解@ConfigurationProperties(prefix = “hello”)是获取配置文件的配置前缀为hello的值,然后赋值给msg变量

@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
    private static final String MSG="hello world";
    private String msg=MSG;
    public static String getMSG() {
        return MSG;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

4.写一个自动配置类 MyAutoConfiguration

引用定义好的配置信息;在AutoConfiguration中实现所有starter应该完成的操作,并且把这个类加入spring.factories配置文件中进行声明

@Configuration
@ConditionalOnClass({TestBean.class})//判断当前classpath下是否存在指定类,若是则将当前的配置装载入spring容器
@EnableConfigurationProperties(HelloServiceProperties.class)//激活自动配置(指定文件中的配置)
public class MyAutoConfiguration {
    @Autowired
    HelloServiceProperties helloServiceProperties;//注入测试的配置信息类
    @Bean
    @ConditionalOnMissingBean(TestBean.class) //当前上下文中没有TestBean实例时创建实例
    public TestBean getTestService(){
        TestBean testBean=new TestBean();
        testBean.setMsg(helloServiceProperties.getMsg());
        return testBean;
    }
}

5.新建spring.factories

在resources文件夹下新建文件夹META-INF/spring.factories,将上面的自定义配置类MyAutoConfiguration的全路径名+类名配置到该文件中(遵循spring.factories的格式),这样随着项目的启动就可以实现自动装配!

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.ftx.tomcat.bean.MyAutoConfiguration

mvn打包

Idea选择Edit Configuration -》 + -》 搜索Maven -》输入命令 clean package install
在这里插入图片描述

6.新建SpringBoot项目

将刚才打包好的maven依赖导入到SpringBoot项目依赖中

7.测试

在新建的springboot项目中写一个TestController进行测试
注入TestBean,并使用TestBean

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    TestBean testBean;
    @GetMapping("/getTest")
    public String getTest(){
        return testBean.getMsg();
    }
}

启动项目,访问http://localhost:8088/test/getTest
在这里插入图片描述


版权声明:本文为mamingshifan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/mamingshifan/article/details/127902854