初學spring-boot遇到的自定義屬性獲取問題
遇到如下一些問題:(springboot-1.5.14)
1.自己建立的包一定要在啟動入口類
***Application.java
包下,這樣@EnableAutoConfiguration
註解才會自動掃描package,建立Beans
2.當我們需要自定義配置時,
@EnableConfigurationProperties
功能是自動對映一個POJO
到SpringBoot
配置檔案(預設是application.properties
檔案)的屬性集。
下面我們看下我自己做的一個小demo
1.首先在resources/application.properties
檔案中寫下如下配置:
gt.name=cronous
gt.describe=cool boy
2.首先看一下需要對映的實體類
package edu.hohai.myfirstspringboot.gt.entity;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component //代表這是一個bean元件
@ConfigurationProperties(prefix = "gt") //application.properties檔案中的自定義配置字首prefix
public class Blog {
private String name;
private String describe;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescribe() {
return describe;
}
public void setDescribe (String describe) {
this.describe = describe;
}
}
3.看下最原始的入口類
package edu.hohai.myfirstspringboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableAutoConfiguration
public class MyfirstSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MyfirstSpringBootApplication.class, args);
}
}
4.再看一下我的pom.xml
配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.hohai</groupId>
<artifactId>myfirst-spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>myfirst-spring-boot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.14.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<!--spring boot 配置處理器(用於讀取application.properties的配置) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--測試依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
5.我的測試類
package edu.hohai.myfirstspringboot;
import edu.hohai.myfirstspringboot.gt.entity.Blog;
import edu.hohai.myfirstspringboot.gt.web.HelloController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
//基於1.5.14的mock測試用例
@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
@EnableConfigurationProperties(Blog.class) //記得一定要繫結配置檔案到POJO類,不然會無法建立bean
public class MyfirstSpringBootApplicationTests{
@Autowired
private MockMvc mvc;
@Autowired
private Blog blog;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test //用於測試自己寫的/hello路由請求,這裡我們不關心這個,看下面的自定義屬性測試
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("cronous"));
}
@Test //自定義屬性配置的測試
public void getProperty() throws Exception {
System.out.println(blog.getName());
System.out.println(blog.getDescribe());
}
}
如果少了繫結彙報如下錯誤:
2018-07-15 17:50:55.781 ERROR 4444 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.a[email protected]6166e06f] to prepare test instance [[email protected]b58ca3]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'edu.hohai.myfirstspringboot.MyfirstSpringBootApplicationTests': Unsatisfied dependency expressed through field 'blog'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'edu.hohai.myfirstspringboot.gt.entity.Blog' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1272) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118) ~[spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) ~[spring-boot-test-autoconfigure-1.5.14.RELEASE.jar:1.5.14.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'edu.hohai.myfirstspringboot.gt.entity.Blog' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.18.RELEASE.jar:4.3.18.RELEASE]
... 28 common frames omitted
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'edu.hohai.myfirstspringboot.MyfirstSpringBootApplicationTests': Unsatisfied dependency expressed through field 'blog'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'edu.hohai.myfirstspringboot.gt.entity.Blog' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1272)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'edu.hohai.myfirstspringboot.gt.entity.Blog' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 28 more
2018-07-15 17:50:55.810 INFO 4444 --- [ Thread-3] o.s.w.c.s.GenericWebApplicationContext : Closing org.s[email protected]1cbb87f3: startup date [Sun Jul 15 17:50:50 CST 2018]; root of context hierarchy
Process finished with exit code -1
我也把controller類貼出來吧,不然不完整
package edu.hohai.myfirstspringboot.gt.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index(){
return "cronous";
}
}
6.列印如下所示,說明我們成功獲取
2018-07-15 18:29:24.897 INFO 4336 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 7 ms
cronous
cool boy
2018-07-15 18:29:24.931 INFO 4336 --- [ Thread-3] o.s.w.c.s.GenericWebApplicationContext : Closing org.s[email protected]15bbf42f: startup date [Sun Jul 15 18:29:18 CST 2018]; root of context hierarchy
Process finished with exit code 0
相關推薦
Spring Boot thymeleaf 自定義標籤獲取標籤屬性值 EL表示式的值
關鍵點有兩點,第一,優先順序要比100大,下面圖片能看到,我這個定義的是 90000,其次在寫標籤的屬性,比如 value這個值吧 ,不能直接寫 value="${xxx.xxx}" 必須要寫 th:value="${xxx.xxx}" ,真實坑,官網沒有說明,好費勁
初學spring-boot遇到的自定義屬性獲取問題
遇到如下一些問題:(springboot-1.5.14) 1.自己建立的包一定要在啟動入口類***Application.java包下,這樣@EnableAutoConfiguration註解才會自動掃描package,建立Beans 2.
spring boot 新增自定義配置檔案並讀取屬性
"123" "pcq" spring 屬性檔案預設配置檔案是從application.properties讀取的, 但是我想把配置檔案分開,比如 業務的我想放在biz.properties, 客戶端配置的放在client.properties , 但是注入呢,經過測試可以這
spring boot中自定義properties檔案並獲取內容
http://zk-chs.iteye.com/blog/2281978 最近專案中使用到了spring boot,這次帶來點關於spring boot中properties檔案的使用方法 首先你可以定義一個properties檔案,如下所示: Java程式
Spring Boot 引入自定義yml
abstract profile boot pos 人性化 trac cnblogs bstr strac 喜歡yml配置文件格式的人性化,也喜歡properties配置文件管理方式的人性化, 那麽下面我們就來看一下 yml 是如何配置和使用類似properties管理方
spring boot讀取自定義配置類
原理:在本地或者專案的配置檔案裡 寫了一些屬性,把這些屬性封裝到編寫的類裡,什麼地方需要就把該類注入即可 spring boot 1.5版本之前的寫法 第一步 定義配置類 配置類要實現版本號要有get/set方法 可以用@Data實現省去set與get lokback功能 只需要
spring boot之自定義錯誤頁面
spring boot之自定義錯誤頁面 1.在resource-templates資料夾下新建error資料夾 在error 檔案裡建立自己的錯誤頁面 2.自定義錯誤異常處理類 @ControllerAdvice //用於攔截全域性的controller
spring boot 讀取自定義properties檔案
@Configuration@Componentpublic class PropertiesConfig { private static final String[] properties = {"/application.properties"}; private static Proper
Spring Boot 實現自定義錯誤頁面
sprin 支援實現ErrorController 來自定義錯誤頁面 下面是具體程式碼的實現 @Controller public class CustomErrorController implements ErrorController { @Autowired
spring boot通過自定義註解和AOP攔截指定的請求
本文主要通過切面類和自定註解的方式,攔截指定的介面(程式碼中已經作了詳細的說明) 目錄 一 準備工作 三 切面類 五 測試結果 一 準備工作 1.1 新增依賴 通過spr
spring boot log4j2 自定義級別日誌並存儲,超詳細
由於需要一些業務日誌,本來是用的註解,然後用spring aop獲取註解的形式來記錄,但是由於最開始的時候沒有統一controller 方法的引數,引數資料,細緻到id不太好記錄。於是想到了log4j的形式儲存資料庫,但log4j的形式記錄會記錄所有級別的日誌,即使指定日誌級
在Spring boot中自定義RabbitMQ的messageConverter
@Configuration public class GlobalConfig { //以下配置RabbitMQ訊息服務 @Autowired public ConnectionFactory connectionFactory; @Bean public
Spring boot中自定義Json引數解析器
轉載請註明出處。。。 一、介紹 用過springMVC/spring boot的都清楚,在controller層接受引數,常用的都是兩種接受方式,如下 1 /** 2 * 請求路徑 http://127.0.0.1:8080/test 提交型別為application/json 3
Spring boot中自定義Json參數解析器
分享圖片 star 搭建 convert ner 方法註入 DDU handler format 轉載請註明出處。。。 一、介紹 用過springMVC/spring boot的都清楚,在controller層接受參數,常用的都是兩種接受方式,如下 1 /** 2
Spring boot logback自定義配置
1.Springboot預設使用logback日誌,因此不用加logback maven依賴,只需新增日誌配置檔案即可,新增日誌檔案logback-spring.xml,內容如下: <?xml version="1.0"encoding="UTF-8"?> &l
Spring Boot新增自定義Filter
第一步:編寫自己的Filter public class MyFilter implements Filter { public void doFilter(ServletRequest
javascript根據元素自定義屬性獲取元素,操作元素
function getElementByAttr(tag,attr,value) { var aElements=document.getElementsByTagName(tag); var aEle=[]; for(var
SpringBoot(五):自定義屬性獲取
目錄 一.全域性配置檔案配置屬性 二.獲取單一屬性 三.對映Bean屬性 四.測試 一.全域性配置檔案配置屬性 在src/main/resources目錄下,找到一個名為application-dev.properties的全域性配置檔案,可
Spring boot 引用自定義配置文件
npr urn str spro tle control ons void mpi 依賴jar <dependency> <groupId>org.springframework.boot</groupId> <
spring boot載入自定義配置源
概述 我們知道,在Spring boot中可以通過xml或者@ImportResource來引入自己的配置檔案,但是這裡有個限制,必須是本地,而且格式只能是 properties(或者 yaml)。那麼,如果我們有遠端配置,如何把他引入進來來呢。 第一種方式 這外一種方法