sourcecode

java.util용 Spring JavaConfig.속성 필드

codebag 2023. 8. 26. 11:21
반응형

java.util용 Spring JavaConfig.속성 필드


spring javaconfig를 사용하여 java.util에 속성 파일을 직접 로드/자동 배선하는 방법을 알려줄 수 있습니까?속성 필드?

감사합니다!

나중에 편집 - 여전히 답을 검색합니다.Spring JavaConfig를 사용하여 속성 파일을 java.util에 직접 로드할 수 있습니까?속성 필드?

XML 기본 방식:

스프링 구성:

<util:properties id="myProperties" location="classpath:com/foo/my-production.properties"/>

클래스:

@Autowired
@Qualifier("myProperties")
private Properties myProperties;

JavaConfig 전용

주석이 있는 것 같습니다.

@PropertySource("classpath:com/foo/my-production.properties")

이것으로 클래스에 주석을 달면 파일의 속성이 환경에 로드됩니다.그런 다음 속성을 가져오려면 환경을 클래스에 자동으로 연결해야 합니다.

@Configuration
@PropertySource("classpath:com/foo/my-production.properties")
public class AppConfig {

@Autowired
private Environment env;

public void someMethod() {
    String prop = env.getProperty("my.prop.name");
    ...
}

Java.util.properties에 직접 주입할 방법이 없습니다.그러나 이 주석을 래퍼 역할을 하는 클래스를 만들고 속성을 그런 식으로 작성할 수 있습니다.

을 선언합니다.PropertiesFactoryBean.

@Bean
public PropertiesFactoryBean mailProperties() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("mail.properties"));
    return bean;
}

레거시 코드의 구성은 다음과 같습니다.

<bean id="mailConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:mail.properties"/>
</bean>

위와 같이 Java 구성으로 변환하는 것은 매우 쉽습니다.

그것은 오래된 주제이지만 더 기본적인 해결책도 있습니다.

@Configuration
public class MyConfig {
    @Bean
    public Properties myPropertyBean() {
        Properties properties = new Properties();
        properties.load(...);
        return properties;
    }
}

xml 구성을 사용하여 직접 속성을 주입하는 방법도 있습니다.컨텍스트 xml에 다음이 있습니다.

<util:properties id="myProps" location="classpath:META-INF/spring/conf/myProps.properties"/>

그리고 자바 클래스는 그냥 사용합니다.

@javax.annotation.Resource
private Properties myProps;

Voila!! 장전됩니다.Spring은 xml의 'id' 특성을 사용하여 코드의 변수 이름에 바인딩합니다.

해보세요.

@Configuration  
public class PropertyConfig { 

 @Bean("mailProperties")  
 @ConfigurationProperties(prefix = "mail")   
  public Properties getProperties() {
     return new Properties();  
  }

}

application.properties에서 속성을 정의해야 합니다.

application.yml:

root-something:
    my-properties:
        key1: val1
        key2: val2

당신의 안전한 포조:

import java.util.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "root-something")
public class RootSomethingPojo {

    private Properties myProperties;

컨테이너 구성:

@Configuration
@EnableConfigurationProperties({ RootSomethingPojo .class })
public class MySpringConfiguration {

이렇게 하면 키-값 쌍이 직접 입력됩니다.myProperties들판.

언급URL : https://stackoverflow.com/questions/15387282/spring-javaconfig-for-java-util-properties-field

반응형