• 自定义自动配置


    所谓自动配置,就是没有显示声明扫描或者配置一个Bean,但是当某些条件触发后,这些Bean就会被纳入Spring管理,并且能够对这些Bean进行一些初始化配置(主要通过配置文件)

    需求:只要存在HelloService,就自动配置这个Bean

    pom

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wisely</groupId>
    <artifactId>spring-boot-starter-hello</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-starter-hello</name>
    <url>http://maven.apache.org</url>

    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>1.5.1.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
    </dependency>
    </dependencies>
    </project>




    自动配置类

    package com.wisely;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    /**
    * Created by sherry on 17/2/16.
    */
    @Configuration
    @ConditionalOnClass(HelloService.class)
    @ConditionalOnProperty(prefix = "hello",value = "enabled",matchIfMissing = true)
    public class HelloServiceAutoConfiguration {

    @Autowired
    private HelloServiceYml helloServiceYml;

    @Bean
    @ConditionalOnMissingBean(HelloService.class)
    public HelloService helloService(){
    HelloService helloService = new HelloService();
    helloService.setMsg(helloServiceYml.getMsg());
    return helloService;
    }

    }


    将这个jar发布后,只要引入这个jar,并且项目中存在HelloService类,不需要配置,就会被Spring管理
  • 相关阅读:
    RedHat Linux AS 5下memcached的安装
    System.Diagnostics.Debug和System.Diagnostics.Trace
    设置c#windows服务描述及允许服务与桌面交互的几种方法
    在WinForm中使用WebServices来实现软件自动升级(AutoUpdate)(C#)
    从客户端中检测到有潜在危险的 Request.Form 值
    discuz数据库迁移,改密码后,相关配置文件修改
    C#取得页面执行时间的代码
    RedHat 解决 ifconfig命令不能使用的问题
    System.ServiceProcess 命名空间下10个类的列表
    Excel导入,导出,模板生成公共模块整理
  • 原文地址:https://www.cnblogs.com/sherrykid/p/6419458.html
Copyright © 2020-2023  润新知