IDEA中创建拥有自定义start的springboot工程——开源项目代码学习

 

步骤1:建立外模块,外模块负责环境配置和加载。

 

步骤2;建立内模块,内模块含有main方法,属于启动模块。

 

工程结构:

  

 

 

外模块示例:

  (1)定义服务Bean:

public class  HelloService {
    private String msg;
    public String sayHello(){
        return "hello " + msg;
    }

    public String getMsg() {
        return msg;
    }

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

  (2)定义另一个服务Bean:使用@ConfigurationProperties,将properties文件中的属性注入Bean的字段

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
    private static final String MSG = "world";
    private String msg = MSG;

    public String getMsg() {
        return msg;
    }

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

  (3)创建主配置类

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
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;

@Configuration  //表明是配置类
@EnableConfigurationProperties(HelloServiceProperties.class)    //
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello",value = "enable",matchIfMissing = true)
public class HelloServiceAutoConfiguration {
    @Autowired
    private HelloServiceProperties helloServiceProperties;
    @Bean
    public HelloService helloService() {
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}

  (4)配置spring.factories:

 

 

 

内模块示例:

   (1)创建启动类

import com.yrc.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class UseMyStarterApplication {

    @Autowired
    private HelloService helloService;

    @RequestMapping("/")
    public String index(){
        return helloService.sayHello();
    }
    public static void main(String[] args) {
        SpringApplication.run(UseMyStarterApplication.class, args);
    }
}

  (2)配置资源:

 

posted @ 2020-05-24 18:35  Yrc的楚门的世界  阅读(655)  评论(0)    收藏  举报