source

@PropertySource 주석을 사용할 때 값이 확인되지 않았습니다.PropertySourcesPlaceholderConfigurer을 구성하는 방법은 무엇입니까?

factcode 2023. 9. 6. 22:25
반응형

@PropertySource 주석을 사용할 때 값이 확인되지 않았습니다.PropertySourcesPlaceholderConfigurer을 구성하는 방법은 무엇입니까?

구성 클래스는 다음과 같습니다.

@Configuration
@PropertySource(name = "props", value = "classpath:/app-config.properties")
@ComponentScan("service")
public class AppConfig {

그리고 전 재산으로 봉사를 하고 있습니다.

@Component 
public class SomeService {
    @Value("#{props['some.property']}") private String someProperty;

AppConfig 구성 클래스를 다음과 같이 테스트하려는 경우 오류가 발생함

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String service.SomeService.someProperty; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'props' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' 

이 문제는 SPR-8539에 문서화되어 있습니다.

어쨌든 PropertySourcesPlaceholderConfigurer을 구성하여 작동시키는 방법을 알 수 없습니다.

편집 1

이 접근 방식은 xml 구성에서 잘 작동합니다.

<util:properties id="props" location="classpath:/app-config.properties" />

구성은 자바를 사용하고 싶습니다.

@cwash 말대로

@Configuration
@PropertySource("classpath:/test-config.properties")
public class TestConfig {

     @Value("${name}")
     public String name;


     //You need this
     @Bean
     public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
     }

}

@PropertySource를 사용하는 경우 속성을 다음과 같이 검색해야 합니다.

@Autowired
Environment env;
// ...
String subject = env.getProperty("mail.subject");

을 하여 하려는 하려는 으로 검색하려면@Value("${mail.subject}")xml., xml로 .

사유 : https://jira.springsource.org/browse/SPR-8539

나는 라는 .@value 것은,게지던건이건던s지이,게te@value필요한 하는PropertySourcesPlaceholderConfigurer에 대신에PropertyPlaceholderConfigurer 효과가 3 릴리즈를 . 저도 같은 변경을 했고 효과가 있었습니다. 스프링 4.0.3 릴리즈를 사용하고 있습니다.저는 제 컨피규레이션 파일에 아래 코드를 사용하여 구성하였습니다.

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
   return new PropertySourcesPlaceholderConfigurer();
}

@Configuration 클래스에서 @PropertySourcePlaceholderConfigurer을 반환하고 주석이 달린 @Bean 및 정적인 메서드가 필요하지 않습니까?

http://www.baeldung.com/2012/02/06/properties-with-spring/ #https

https://jira.springsource.org/browse/SPR-8539

저도 똑같은 문제가 있었습니다.@PropertySource잘 놀아나지 않습니다.@Value빠른 은 를 을 설정하는 입니다. 를 사용하면 됩니다.@ImportResource와 같이 에는 다음과 같은 항목이 됩니다:으로 XML성일다이는다이s:일성yaee로는ltl .<context:property-placeholder />(물론 필요한 네임스페이스 세리머니와 함께).@Value는 당신의의을할다에r에 속성을 주입할 입니다.@Configuration

자바에서도 이렇게 구성할 수 있습니다.

@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setIgnoreUnresolvablePlaceholders(true);
    configurer.setIgnoreResourceNotFound(true);
    return configurer;
}

굉장히 복잡해 보이는데, 그냥 할 수는 없나요?

 <context:property-placeholder location="classpath:some.properties" ignore-unresolvable="true"/>

코드 참조:

@Value("${myProperty}")
private String myString;

@Value("${myProperty.two}")
private String myStringTwo;

some.properties는 이런 식으로 보입니다.

myProperty = whatever
myProperty.two = something else\
that consists of multiline string

자바 기반 구성의 경우 이 작업을 수행할 수 있습니다.

@Configuration
@PropertySource(value="classpath:some.properties")
public class SomeService {

에 그냥 을 이용해서 .@value전과 다름없이

4 사용 Since Spring 4.3 RC2 PropertySourcesPlaceholderConfigurer아니면<context:property-placeholder>더 이상 필요하지 않습니다.우리는 직접 사용할 수 있습니다.@PropertySource와 함께@Value. 이 Spring framework 티켓 보기

Spring 5.1.3으로 테스트 어플리케이션을 만들었습니다.릴리스. 더application.properties에는 다음 두 쌍이 포함됩니다.

app.name=My application
app.version=1.1

AppConfig을해을다합니다 를 통해 속성을 합니다.@PropertySource.

package com.zetcode.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = "application.properties", ignoreResourceNotFound = true)
public class AppConfig {

}

Application다음을 통해 특성을 주입합니다.@Value그것들을 사용합니다.

package com.zetcode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.zetcode")
public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    public static void main(String[] args) {

        var ctx = new AnnotationConfigApplicationContext(Application.class);
        var app = ctx.getBean(Application.class);

        app.run();

        ctx.close();
    }

    public void run() {

        logger.info("Application name: {}", appName);
        logger.info("Application version: {}", appVersion);
    }
}

출력은 다음과 같습니다.

$ mvn -q exec:java
22:20:10.894 [com.zetcode.Application.main()] INFO  com.zetcode.Application - Application name: My application
22:20:10.894 [com.zetcode.Application.main()] INFO  com.zetcode.Application - Application version: 1.1

문제는 제가 알기로는 <http:propertes id="id" location="loc"/>는 단지 의 축약어일 뿐입니다.

<bean id="id" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="loc"/>
</bean>

(util:properties의 설명서 참조).따라서 util:properties를 사용하면 독립 실행형 빈이 생성됩니다.

@PropertySource 반면, 문서에 따르면 다음과 같습니다.

봄의 환경에 속성 소스를 추가하기 위한 편리하고 선언적인 메커니즘을 제공하는 주석.

(@PropertySource 문서 참조).그래서 어떤 콩도 만들지 않습니다.

그러면 "#{a[something]}"는 SpEL 표현이며, "빈 'a'에서 무언가를 얻는다"는 의미입니다.util:properties를 사용하면 빈이 존재하고 의미있는 표현이지만 @PropertySource를 사용하면 실제 빈이 존재하지 않고 의미없는 표현입니다.

XML을 사용하거나(가장 좋은 방법이라고 생각합니다) PropertiesFactoryBean을 직접 발행하여 일반 @Bean으로 선언하여 이 문제를 해결할 수 있습니다.

발생할 수 있는 또 다른 문제는 @Value 주석이 달린 값이 정적이지 않은지 확인하는 것입니다.

제 경우, dependence-on="bean1"이 property-placeholder 내에 있어서 문제를 일으켰습니다.저는 이 의존성을 제거하고 @PostConstruct를 사용하여 동일한 원래 기능을 달성했으며 새 값도 읽을 수 있었습니다.

xml을 사용하여 구성하는 경우 추가한

<target:smarget-placeholder 위치="..."/">

주석이 활성화되었는지 확인합니다.이러한 이유로 속성을 가져오지 못했습니다.

<파일:인증-config/>

나에게는 효과가 있었습니다.

spring.cloud.config.server.git.default-label=main spring.cloud.config.server.server.spring입니다.Locations=file://Users/${your username}/Projects/git-local-reposities/spring.spring.active=file

언급URL : https://stackoverflow.com/questions/13728000/value-not-resolved-when-using-propertysource-annotation-how-to-configure-prop

반응형