春ブーツ

Spring Bootアプリケーションが構成ファイルの構成情報を取得する方法:

1. @Valueアノテーションを介して取得する

2. Environmentクラスを通じて取得

3. @ConfigurationPropertiesから取得する

Application.propertiesファイルの内容:

1 server.port = 8080
 2  
3  
4 spring.main.banner-mode = off
 5  
6 myconfig.mail.port = 1234
コードを表示

 

myconfig.propertiesファイルの内容:

1 myconfig.mail.address = localhost
 2 myconfig.mail.userName = myuser
コードを表示

 

HelloController.javaファイルの内容:

1  インポートjavax.annotation.Resource;
2  
3  import org.springframework.beans.factory.annotation.Autowired;
4  org.springframework.beans.factory.annotation.Valueをインポートします。
5  org.springframework.boot.context.properties.ConfigurationPropertiesをインポートします。
6  import org.springframework.context.annotation.Configuration;
7  import org.springframework.context.annotation.PropertySource;
8  import org.springframework.core.env.Environment;
9  org.springframework.stereotype.Componentをインポートします。
10  インポートorg.springframework.web.bind.annotation.RequestMapping;
11  import org.springframework.web.bind.annotation.RestController;
12  
13  @RestController
 14  public  class HelloController {
 15      @Resource
 16      private Environment environment;
17      
18      @Value( "$ {server.port}" 19      プライベート文字列ポート。
20      
21      @Autowired
 22      MyconfigProperties myconfig;
23      
24      @RequestMapping( "/ hello" 25      public String Hello(){
26          System.out.println( "server.port =" + environment.getProperty( "server.port" ));
27          System.out.println( "server.port =" + port);
28          
29          System.out.println( "address =" + myconfig.getAddress()+ "、userName =" + myconfig.getUserName()+ "、port =" + myconfig.getPort());
30          
31          return "Hello world!" ;
32      }
 33  }
 34  
35  @Component
 36 @PropertySource({"classpath:myconfig.properties"、 "classpath:application.properties" クラスMyconfigProperties {
 39      プライベート文字列アドレス。
40      プライベート文字列userName;
41      プライベート整数ポート。
42      
43      public Integer getPort(){
 44          戻りポート。
45      }
 46      public  void setPort(Integer port){
 47          this .port = port;
48      }
 49      public String getAddress(){
 50          return address;
51      }
 52      パブリック ボイドsetAddress(String address){
 53          this .address = address;
54      }
 55      
56      public String getUserName(){
 57          return userName;
58      }
 59      public  void setUserName(String userName){
 60          this .userName = userName;
61      }
 62 }
コードを表示

 

おすすめ

転載: www.cnblogs.com/labing/p/12729537.html