Spring Boot 构建新番一

针对 https://blog.csdn.net/kangguang/article/details/104062422 中构建完成后第一种情况,出现认知的第一个错误,自动生成的配置中,不需要配置web 的tomcat 也可以用spring内嵌的tomcat进行测试运行,只是不自动打开网页展示效果!

一、通过配置

1.在application.properties文件中配置

//环境切换
spring.profiles.active= dev //测试环境
//站点名称
server.servlet.context-path=/website
helloWorld = Hello SpringBoot!
//日志写入路径
logging.file.path= /Users/kangxg/Desktop/ideaJava/mylog/log.lo

spring.profiles.active= dev 是 选择测试环境配置,在同目录下创建application-dev.properties和application-prod.properties

application-dev.properties: server.port= 8888

application-prod.properties:server.port= 80

2.创建HelloWorldController

@RestController
public class HelloWorldController {
    @Value("${helloWorld}")
    private String hello;
    @RequestMapping("/hello")
    public String hello()
    {
        return  hello;
    }
}

3.debug运行 并在浏览器中输入http://localhost/website/hello

二、利用自定义配置类进行属性设置

 1.application.properties:

//环境切换 测试环境
spring.profiles.active= dev 
//站点名称
server.servlet.context-path=/website
helloWorld = Hello SpringBoot!
//日志写入路径
logging.file.path= /Users/kangxg/Desktop/ideaJava/mylog/log.log

jdbc.driver    = com.mysql.jdbc.Driver
jdbc.url       = jdbc:mysql://localhost:3306/mybatis
jdbc.username  = root
jdbc.password  = kangxg198811

2.自定义配置类MysqlProperties:

@Component
@ConfigurationProperties(prefix = "jdbc")
public class MysqlProperties {
    private String driver;
    private String url;
    private String username;
    private String password;

    public String getDriver()
    {
        return driver;
    }
    public  String getUrl()
    {
        return  url;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUrl(String url) {
        this.url = url;
    }

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

3.HelloWorldController:

@RestController
public class HelloWorldController {
    @Value("${helloWorld}")
    private String hello;

    @Resource
    private  MysqlProperties mysqlProperties;
    @RequestMapping("/hello")
    public String hello()
    {
        return  hello;
    }
    @RequestMapping("/showjdbc")
    public String showjdbc()
    {

        return "mysql.jdbcname:"+mysqlProperties.getDriver()+"<br/>"
                +"mysql.dbUrl:"+mysqlProperties.getUrl()+"<br/>"
                +"mysql.username:"+mysqlProperties.getUsername()+"<br/>"
                +"mysql.password:"+mysqlProperties.getPassword();
    }
}

4.debug 运行 浏览器中访问

发布了255 篇原创文章 · 获赞 39 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/kangguang/article/details/104069880
今日推荐