一、@RestController和@Controller的区别
- @RestController注解相当于@ResponseBody + @Controller合在一起的作用。
- 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。例如:本来应该到success.jsp页面的,则其显示success.
- 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
- 如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
二、ConfigurationProperties配置方式
2.1 配置一个MySqlProperties
package com.shyroke.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "mysql") public class MySqlProperties { private String jdbcName; private String dbUrl; private String userName; private String password; public String getJdbcName() { return jdbcName; } public void setJdbcName(String jdbcName) { this.jdbcName = jdbcName; } public String getDbUrl() { return dbUrl; } public void setDbUrl(String dbUrl) { this.dbUrl = dbUrl; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2.2 配置application.properties
server.port=8088 welcome=spring boot \u4F60\u597D mysql.jdbcName=com.mysql.jdbc.Driver mysql.dbUrl=jdbc:mysql://localhost:3306/db_boot mysql.userName=root mysql.password=
2.3 编写控制器
package com.shyroke.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.shyroke.config.MySqlProperties; @RestController @RequestMapping(value="/hello") public class HelloWorldController { @Value("${welcome}") private String welcome; @Autowired private MySqlProperties MySqlProperties; @RequestMapping(value="/login") public String login() { return "mysql.jdbcName:"+MySqlProperties.getJdbcName()+"<br/>" +"mysql.dbUrl:"+MySqlProperties.getDbUrl()+"<br/>" +"mysql.userName:"+MySqlProperties.getUserName()+"<br/>" +"mysql.password:"+MySqlProperties.getPassword(); } }
2.4 结果