Spring Boot自动配置实战 1、新建Spring-boot-starter-hello项目。 2、新建HelloService.java
package com.tzp.helloworld.helloservice; public class HelloService { private String msg; public String sayHello() { return "=======>>" + msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
2、新建HelloServiceProperties.java
package com.tzp.helloworld.helloproperties; 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、新建HelloServiceAutoConfigration.java
package com.tzp.helloworld.helloServiceConfigration; 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.ConditionalOnMissingClass; 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; import com.tzp.helloworld.helloproperties.HelloServiceProperties; import com.tzp.helloworld.helloservice.HelloService; @Configuration @EnableConfigurationProperties(HelloServiceProperties.class) @ConditionalOnClass(HelloService.class) @ConditionalOnProperty(prefix = "hello",value = "enabled",matchIfMissing = true) public class HelloServiceAutoConfigration { @Autowired private HelloServiceProperties helloServiceProperties; @Bean @ConditionalOnMissingBean(HelloService.class) public HelloService helloService() { HelloService helloService = new HelloService(); helloService.setMsg(helloServiceProperties.getMsg()); return helloService; } }
4、mvn install将项目打成jar包,并将jar包添加到本地maven仓库。5、接下来我们就可以在别的工程上使用该jar包了。
<dependency> <groupId>com.tzp</groupId> <artifactId>spring-boot-starter-hello</artifactId> <version>1.0.0</version> </dependency>
hello: msg: 唐增平的springboot
package com.tzp.helloworld.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.tzp.helloworld.helloservice.HelloService; @RestController public class HelloSpringBoot { @Value("${melo.name}") private String name; @Autowired private HelloService helloService; @RequestMapping("/") public String hello() { return "hello spring boot " + name + helloService.getMsg(); } }
6、运行项目并访问。
原文地址:https://www.cnblogs.com/zengpingtang/p/10803706.html
时间: 2024-11-07 07:16:49