spring boot 常见问题

 

目录

一个接口有多个实现类的Spring注入方式

@Controller和@RestController的区别? 

配置文件如何加载到类文件中 

使用Spring boot实现异常处理


一个接口有多个实现类的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注解。

配置文件如何加载到类文件中 

  1. @SpringBootApplication

  2. @PropertySource(value={"file:config.properties"})

  3. 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类,来处理控制器类抛出的所有异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值