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配合。java

即@RestController是@ResponseBody和@Controller的組合註解。spring

@RestController
public class HelloController {

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

1.3 @RequestMapping 配置url映射

@RequestMapping此註解便可以做用在控制器的某個方法上,也能夠做用在此控制器類上;@RequestMapping中的method參數有不少中選擇,通常使用get/post.json

當控制器在類級別上添加@RequestMapping註解時,這個註解會應用到控制器的全部處理器方法上。處理器方法上的@RequestMapping註解會對類級別上的@RequestMapping的聲明進行補充。api

看兩個例子:springboot

例子一:@RequestMapping僅做用在處理器方法上

@RestController
public class HelloController {

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

以上代碼sayHello所響應的url=localhost:8080/hello。app

例子二:@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,post

                                sayHi所響應的url=localhost:8080/hello/sayHi。this

2. 獲取配置信息經常使用註解@Value,@ConfigurationProperties,@PropertySource

 2.1 Spring-@value用法詳解

爲了簡化讀取properties文件中的配置值,spring支持@value註解的方式來獲取,這種方式大大簡化了項目配置,提升業務中的靈活性。url

1、兩種使用方法

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

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

2、配置

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的配置文件基礎上增長:

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

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

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 }

咱們來具體分析下:

一、@Component註解說明這是一個普通的bean,在Component Scanning時會被掃描到並被注入到Bean容器中;咱們能夠在其它引用此類的地方進行自動裝配。@Autowired這個註解表示對這個bean進行自動裝配。 好比:

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

二、@PropertySource註解用來指定要讀取的配置文件的路徑從而讀取這些配置文件,能夠同時指定多個配置文件;

三、@Value("${connect.api.apiKeyId}")用來讀取屬性key=connect.api.apiKeyId所對應的值並把值賦值給屬性apiKeyId;

四、經過提供的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 }

 附:

配置文件

local.ip=192.163.1.1
local.port=8080
name=springboot
app.name=this is ${name}

UserConfig.java

 1 package com.example.properties;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Value;
 5 import org.springframework.context.annotation.PropertySource;
 6 import org.springframework.core.env.Environment;
 7 import org.springframework.stereotype.Component;
 8 /*
 9  * 兩種獲取配置的方法
10  * 配置文件目錄 能夠在當前目錄 也能夠在當前目錄下的config 目錄中
11  * 配置文件能夠在 --spring.config.name來指定
12  * 配置文件目錄路徑可使用--spring.config.location來指定  或者使用@PropertySource註解
13  */
14 @Component
15 public class UserConfig {
16     @Value("${local.port}")
17     private String LocalPort;
18     @Autowired
19     private Environment env;
20     public void show() {
21         System.out.println("Local.port:"+LocalPort);
22         System.out.println("local.ip:"+env.getProperty("local.ip"));
23         System.out.println("name:"+env.getProperty("name"));
24         System.out.println("app.name:"+env.getProperty("app.name"));
25     }
26 }

 Environment

 Environment是Spring核心框架中定義的一個接口,用來表示整個應用運行時的環境,也就是說Spring抽象了一個Environment來表示環境配置。

相關文章
相關標籤/搜索