目录
@Controller和@RestController的区别?
一个接口有多个实现类的Spring注入方式
一个接口,如果有多个实现类impl,那进行spring 注入的时候,如何区别呢?
1、通过 @Autowired 和 @Qualifier 配合注入
@Autowired
@Qualifier("interface1Impl1")
Interface1 interface1;
2、使用@Resource注入,根据默认类名区分
@Resource(name = "interface1Impl1")
Interface1 interface1;
3、使用@Resource注入,根据@Service指定的名称区分
接口实现类
@Service("s1")
public class Interface1Impl1 implements Interface
注入
@Resource(name = "s1")
Interface1 interface1;
@Controller和@RestController的区别?
RestController注解返回的是数据json、xml等,Controller是跳到ret对应的页面
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
1) 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容(JSON,XML或自定义mediaType内容)。
2) 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。.使用@Controller 注解,在对应的方法上,视图解析器可以解析return 的jsp,html页面,并且跳转到相应页面
如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
配置文件如何加载到类文件中
-
@SpringBootApplication
-
@PropertySource(value={"file:config.properties"})
-
public class SpringbootrestdemoApplication {。。。}
PropertySource这个注解将配置文件引入类
按Profile不同环境读取不同配置
不同环境的配置设置一个配置文件,例如:
- dev环境下的配置配置在application-dev.properties中;
- prod环境下的配置配置在application-prod.properties中。
在application.properties中指定使用哪一个文件
spring.profiles.active = dev
将配置文件中的属性加载到类属性中
配置文件application.properties中配置属性:
test.name = wahaha
test.age = 27
test.tel = 18800118888
引入配置文件中的数据值
1、@Component和@Value("${"xxx"}")
类文件:
@Component
public class Configurations {
@Value("${test.name}")
private String name;
@Value("${test.age}")
private String age;
@Value("${test.tel}")
private Long tel;
// getter and setter
}
2、手动书写@Value还是比较繁重的工作,好在Spring Boot提供了更简洁的方式。@ConfigurationProperties(prefix = "test")。
@Component
@ConfigurationProperties(prefix = "test")
public class Configuration {
private String name;
private String age;
private Long tel;
// setter getter
}
使用Spring boot实现异常处理
spring 提供了一种使用ControllerAdvice处理异常的方法,通过实现一个ControllerAdvice类,来处理控制器类抛出的所有异常