栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自己书写springboot-starter自动装配过程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自己书写springboot-starter自动装配过程

springboot-starter自动装配

第一步新建springboot工程
删除resourses下的文件和启动类
在pom.xml中引入下面几个包

        
            org.springframework.boot
            spring-boot-starter
        

        
        
            org.springframework.boot
            spring-boot-autoconfigure
        

        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        

2.编写加载配置文件的类

@ConfigurationProperties(prefix = "lzj.user")
public class UserProperties {
    private String username = "张三";
    private int age = 15;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

3.编写自动注入的类

@Component
public class UserServices {
    @Resource
    private UserProperties userProperties;
    public void say(){
        System.out.println(userProperties.getUsername()+" dsafas     age is" + userProperties.getAge());
    }
}

4.编写自动配置类

//声明配置类
@Configuration
//加载配置文件的类
@EnableConfigurationProperties({UserProperties.class})
//条件注解在有这个类的时候配置
@ConditionalOnClass(UserServices.class)
//条件注解 当lzj.user.enable=true时配置类生效
@ConditionalOnProperty(prefix = "lzj.user", value = "enable", matchIfMissing = true)
//需要继承InitializingBean接口为bean提供了初始化方法的方式
public class MystartAutoConfig implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
    }

    
    @Bean
    @ConditionalOnMissingBean
    public UserServices getUserServices() {
        return new UserServices();
    }
}

5.在resouses下新建meta-INF/spring.factories

将我们写的自动配置类放到spring.factories文件中
springboot在初始化的时候会自动去扫这个文件,将文件中的类注入到容器中

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.jsu.lzj.spring.boot.autoconfigure.MystartAutoConfig

6.最后修改pom.xml打包安装到本地
build中留下面一个就够了

点击maven的install即可

打包好的jar包的使用时的目录

7.使用
在我们其它项目中就可以通过坐标引用了

8.更加规范的写法
像mybatis的starter一样
上面写的应该是直接自动配置的jar包

新建一个空的maven项目
只是用来管理jar包
只需要在pom.xml中引用我们的autoconfigure的jar包即可

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351025.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号