1、 @RestController
@RestController = @Controller + @ResponseBody
@Controller表明了这个类是一个控制器类
@ResponseBody表示方法的返回值直接以指定的格式写入Http response body中,而不是解析为跳转路径。
@RestController
public class HelloController {
private String name;
@RequestMapping("/hello")
public String hello(){
return "Hello World!";
}
}
2. @ConfigurationProperties
@ConfigurationProperties: 告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;默认从全局配置文件中获取值。
prefix = “person”: 配置文件中哪个下面的所有属性进行一一映射
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private int age;
}
person:
last-name: Vivienne
age: 18
3. @PropertySource
@PropertySource: 加载指定的
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource("classpath:person.properties")
public class Person {
private String lastName;
private int age;
...
}
person.lastName=Sam
person.age=25
4. @ImportResource
导入spring的配置文件,让文件里的内容生效。
SpringBoot中没有配置文件,我们自己编写的配置文件,也不能自动识别;想让Spring的配置文件生效,加载进来。就要用@ImportResource导入进来。@ImportResource标志在一个配置类上。
缺点:太麻烦,SpringBoot一般不用这中方式,一般采用配置类,并用@Bean注入类到容器中#5中
@ImportResource(locations = {"classpath:bean.xml"})
@SpringBootApplication
public class HelloWorldApplication {
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
@Autowired
ApplicationContext context; //SpringBoot自动注入容器
@Test
public void testBean(){
//@ImportResource 写在主启动类上,这样SpringBootTest启动时会合并在主配置类上(@SpringBootApplication)的配置,所以helloController会被加载到容器
System.out.println(context.containsBean("helloController"));
}
}
bean.xml的内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloController" class="com.springboot.controller.HelloController"></bean>
</beans>
5. @Bean
@Bean: 将方法的返回值添加到容器中,bean name默认为方法名, 替代xml中的标签添加组件(上面的<bean id=“helloController”)
@Configuration: 指明当前类是一个配置类,用来替代之前Spring中的配置文件(上面的bean.xml)
@Configuration
public class MyConfig {
@Bean
public HelloController helloController(){
return new HelloController();
}
}
3. @SpringBootApplication, @EnableAutoConfiguration,@AutoConfigurationPackage
在另一篇博客有详细讲解 https://blog.csdn.net/Vivienne_ChenW/article/details/105257561