Springboot 常见注解的使用方法

1. SpringBoot 中常用注解@Controller/@RestController/@RequestMapping介绍

1.1 @Controller 处理http请求

@Controller
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

1.2 @RestController

Spring4之后新加入的注解,原来返回json需要@ResponseBody和@Controller配合。

即@RestController是@ResponseBody和@Controller的组合注解。

@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

1.3 @RequestMapping 配置url映射

@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上;@RequestMapping中的method参数有很多中选择,一般使用get/post.

当控制器在类级别上添加@RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。

看两个例子:

例子一:@RequestMapping仅作用在处理器方法上

@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

以上代码sayHello所响应的url=localhost:8080/hello。

例子二:@RequestMapping仅作用在类级别上

@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

以上代码sayHello所响应的url=localhost:8080/hello,效果与例子一一样,没有改变任何功能。

例子三:@RequestMapping作用在类级别和处理器方法上

@RestController
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(value="/sayHello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
    @RequestMapping(value="/sayHi",method= RequestMethod.GET)
    public String sayHi(){
        return "hi";
    }
}

这样,以上代码中的sayHello所响应的url=localhost:8080/hello/sayHello,

                                sayHi所响应的url=localhost:8080/hello/sayHi。

2. 获取配置信息常用注解@Value,@ConfigurationProperties,@PropertySource

 2.1 Spring-@value用法详解

为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性。

一、两种使用方法

1、@Value("#{configProperties['key']}")

2、@Value("${key}")

二、配置

1.  @Value("#{configProperties['key']}")使用

1.1 配置文件:

配置方法1:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:value.properties</value>
        </list>
    </property>
</bean>
配置方法2:
<util:properties id="configProperties" location="classpath:value.properties"></util:properties>

注:配置1和配置2等价,这种方法需要util标签,要引入util的xsd:

  http://www.springframework.org/schema/util

  http://www.springframework.org/schema/util/spring-util-3.0.xsd"

value.properties

key=1  

ValueDemo.java

1 @Component  
2 public class ValueDemo {  
3     @Value("#{configProperties['key']}")  
4     private String value;  
5   
6     public String getValue() {  
7         return value;  
8     }  
9 }
2.  @Value("${key}")使用

2.1 配置文件

1、在1.1的配置文件基础上增加:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
    <property name="properties" ref="configProperties"/>  
</bean> 

2、直接指定配置文件,完整的配置:

1 @Component  
2 public class ValueDemo {  
3     @Value("${key}")  
4     private String value;  
5   
6     public String getValue() {  
7         return value;  
8     }  
9 } 

2.2 spring boot 使用@ConfigurationProperties

有时候有这样子的情景,我们想把配置文件的信息,读取并自动封装成实体类,这样子,我们在代码里面使用就轻松方便多了,这时候,我们就可以使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类

首先在配置文件里面,这些信息是这样子滴

connection.username=admin
connection.password=kyjufskifas2jsfs
connection.remoteAddress=192.168.1.1

这时候我们可以定义一个实体类在装载配置文件信息

 1 @Component
 2 @ConfigurationProperties(prefix="connection")
 3 public class ConnectionSettings {
 4 
 5     private String username;
 6     private String remoteAddress;
 7     private String password ;
 8 
 9     public String getUsername() {
10         return username;
11     }
12     public void setUsername(String username) {
13         this.username = username;
14     }
15     public String getRemoteAddress() {
16         return remoteAddress;
17     }
18     public void setRemoteAddress(String remoteAddress) {
19         this.remoteAddress = remoteAddress;
20     }
21     public String getPassword() {
22         return password;
23     }
24     public void setPassword(String password) {
25         this.password = password;
26     }
27 
28 }

我们还可以把@ConfigurationProperties还可以直接定义在@bean的注解上,这是bean实体类就不用@Component和@ConfigurationProperties了

 1 @SpringBootApplication
 2 public class DemoApplication{
 3 
 4     //...
 5 
 6     @Bean
 7     @ConfigurationProperties(prefix = "connection")
 8     public ConnectionSettings connectionSettings(){
 9         return new ConnectionSettings();
10 
11     }
12 
13     public static void main(String[] args) {
14         SpringApplication.run(DemoApplication.class, args);
15     }
16 }

然后我们需要使用的时候就直接这样子注入

 1 @RestController
 2 @RequestMapping("/task")
 3 public class TaskController {
 4 
 5 @Autowired ConnectionSettings conn;
 6 
 7 @RequestMapping(value = {"/",""})
 8 public String hellTask(){
 9     String userName = conn.getUsername();     
10     return "hello task !!";
11 }
12 
13 }

如果发现@ConfigurationPropertie不生效,有可能是项目的目录结构问题,你可以通过@EnableConfigurationProperties(ConnectionSettings.class)来明确指定需要用哪个实体类来装载配置信息。

2.3 通过 @PropertySource和@Value 来读取配置文件

先来段java代码:

 1 @Component
 2 @PropertySource(value = {"classpath:common.properties", "classpath:abc.properties"})
 3 public class Configs {
 4 
 5     @Value("${connect.api.apiKeyId}")
 6     public String apiKeyId;
 7 
 8     @Value("${connect.api.secretApiKey}")
 9     public String secretApiKey;
10 
11     public String getApiKeyId() {
12         return apiKeyId;
13     }
14 
15     public String getSecretApiKey() {
16         return secretApiKey;
17     }
18 }

我们来具体分析下:

1、@Component注解说明这是一个普通的bean,在Component Scanning时会被扫描到并被注入到Bean容器中;我们可以在其它引用此类的地方进行自动装配。@Autowired这个注解表示对这个bean进行自动装配。 比如:

1 @Controller
2 public class HomeController {
3 
4     @Autowired
5     private Configs configs;
6 }

2、@PropertySource注解用来指定要读取的配置文件的路径从而读取这些配置文件,可以同时指定多个配置文件;

3、@Value("${connect.api.apiKeyId}")用来读取属性key=connect.api.apiKeyId所对应的值并把值赋值给属性apiKeyId;

4、通过提供的get方法来获取属性值,如:

 1 @Controller
 2 public class HomeController {
 3 
 4     @Autowired
 5     private Configs configs;
 6     
 7     private void decrytCardInfo(AtomRequest req) throws Exception {
 8         req.setCardNo(ChipherUtils.desDecrypt(ChipherUtils.decodeBase64(req.getCardNo()), configs.getCardKey(), Consts.CHARSET_UTF8));
 9     }
10 }

猜你喜欢

转载自www.cnblogs.com/superslow/p/9113551.html