programing

속성 파일에서 값을 읽는 방법

telecom 2023. 3. 31. 21:35
반응형

속성 파일에서 값을 읽는 방법

나는 봄을 사용하고 있다.속성 파일에서 값을 읽어야 합니다.이것은 외부 속성 파일이 아니라 내부 속성 파일입니다.속성 파일은 다음과 같습니다.

some.properties ---file name. values are below.

abc = abc
def = dsd
ghi = weds
jil = sdd

기존 방식이 아닌 속성 파일에서 값을 읽어야 합니다.어떻게 달성할 것인가?스프링 3.0에 대한 최신 접근법이 있습니까?

컨텍스트에서 Property Placeholder를 설정합니다.

<context:property-placeholder location="classpath*:my.properties"/>

다음으로 콩의 속성을 나타냅니다.

@Component
class MyClass {
  @Value("${my.property.name}")
  private String[] myValues;
}

여러 개의 쉼표로 구분된 값을 가진 속성을 구문 분석하려면:

my.property.name=aaa,bbb,ccc

그래도 문제가 해결되지 않으면 속성을 가진 콩을 정의하고 수동으로 주입 및 처리할 수 있습니다.

<bean id="myProperties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath*:my.properties</value>
    </list>
  </property>
</bean>

그리고 콩:

@Component
class MyClass {
  @Resource(name="myProperties")
  private Properties myProperties;

  @PostConstruct
  public void init() {
    // do whatever you need with properties
  }
}

같은 목표를 달성하기 위한 다양한 방법이 있다.봄철에 흔히 사용되는 방법은 다음과 같습니다.

  1. PropertyPlaceholderConfigr 사용

  2. PropertySource 사용

  3. ResourceBundleMessageSource 사용

  4. Properties Factory Bean 사용

    기타..........................................

ds.type는 속성 파일의 키입니다.


「」를 사용합니다.PropertyPlaceholderConfigurer

★★★★★PropertyPlaceholderConfigurer

<context:property-placeholder location="classpath:path/filename.properties"/>

또는

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations" value="classpath:path/filename.properties" ></property>
</bean>

또는

@Configuration
public class SampleConfig {
 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
  //set locations as well.
 }
}

PropertySourcesPlaceholderConfigurer '-', '-', '-', '-'에 접속할 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수, 수.

@Value("${ds.type}")private String attr; 

「」를 사용합니다.PropertySource

봄 에서는 등록하지.PropertyPlaceHolderConfigurer@PropertySource버전 호환성을 이해하기 위한 링크를 찾았습니다.

@PropertySource("classpath:path/filename.properties")
@Component
public class BeanTester {
    @Autowired Environment environment; 
    public void execute() {
        String attr = this.environment.getProperty("ds.type");
    }
}

「」를 사용합니다.ResourceBundleMessageSource

빈 등록-

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  <property name="basenames">
    <list>
      <value>classpath:path/filename.properties</value>
    </list>
  </property>
</bean>

액세스 가치-

((ApplicationContext)context).getMessage("ds.type", null, null);

또는

@Component
public class BeanTester {
    @Autowired MessageSource messageSource; 
    public void execute() {
        String attr = this.messageSource.getMessage("ds.type", null, null);
    }
}

「」를 사용합니다.PropertiesFactoryBean

빈 등록-

<bean id="properties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath:path/filename.properties</value>
    </list>
  </property>
</bean>

클래스에 속성 인스턴스를 연결합니다.

@Component
public class BeanTester {
    @Autowired Properties properties; 
    public void execute() {
        String attr = properties.getProperty("ds.type");
    }
}

컨피규레이션클래스 내

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
   @Autowired
   Environment env;

   @Bean
   public TestBean testBean() {
       TestBean testBean = new TestBean();
       testBean.setName(env.getProperty("testbean.name"));
       return testBean;
   }
}

다음은 그 기능을 이해하는 데 큰 도움이 된 추가 답변입니다.http://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html

Bean Factory Post Processor 빈은 정적 수식자를 사용하여 선언해야 합니다.

@Configuration
@PropertySource("classpath:root/test.props")
public class SampleConfig {
 @Value("${test.prop}")
 private String attr;
 @Bean
 public SampleService sampleService() {
  return new SampleService(attr);
 }

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

@Value를 사용하지 않고 속성 파일을 수동으로 읽어야 하는 경우.

Lokesh Gupta가 잘 쓴 페이지 감사합니다: 블로그

여기에 이미지 설명 입력

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;


public class Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());

    public static Properties fetchProperties(){
        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return properties;
    }
}

다른 방법은 ResourceBundle을 사용하는 것입니다.기본적으로 번들은 '.properties'가 없는 이름을 사용하여 가져옵니다.

private static final ResourceBundle resource = ResourceBundle.getBundle("config");

또한 다음을 사용하여 모든 값을 복구할 수 있습니다.

private final String prop = resource.getString("propName");

PropertyPlaceholderConfigr bean을 응용 프로그램 컨텍스트에 넣고 위치 속성을 설정해야 합니다.

자세한 것은, http://www.zparacha.com/how-to-read-properties-file-in-spring/ 를 참조해 주세요.

이 작업을 수행하려면 속성 파일을 약간 수정해야 할 수 있습니다.

도움이 됐으면 좋겠다.

되지 않는 에 봄의 과 같은 주석은 .@Component,@Configuration하지만 나는 그 수업에서 읽기를 원했다.application.properties

나는 반 학생들이 스프링 콘텍스트에 대해 알게 함으로써 그것을 작동시킬 수 있었다. 그래서 나는 그것을 알고 있다.Environment, 그 때문에,environment.getProperty()정상적으로 동작합니다.

분명히 말하면, 다음과 같습니다.

application.properties

mypath=somestring

Utils.java

import org.springframework.core.env.Environment;

// No spring annotations here
public class Utils {
    public String execute(String cmd) {
        // Making the class Spring context aware
        ApplicationContextProvider appContext = new ApplicationContextProvider();
        Environment env = appContext.getApplicationContext().getEnvironment();

        // env.getProperty() works!!!
        System.out.println(env.getProperty("mypath")) 
    }
}

ApplicationContextProvider.java(Spring get current ApplicationContext 참조)

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext CONTEXT;

    public ApplicationContext getApplicationContext() {
        return CONTEXT;
    }

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        CONTEXT = context;
    }

    public static Object getBean(String beanName) {
        return CONTEXT.getBean(beanName);
    }
}
 [project structure]: http://i.stack.imgur.com/RAGX3.jpg
-------------------------------
    package beans;

        import java.util.Properties;
        import java.util.Set;

        public class PropertiesBeans {

            private Properties properties;

            public void setProperties(Properties properties) {
                this.properties = properties;
            }

            public void getProperty(){
                Set keys = properties.keySet();
                for (Object key : keys) {
                    System.out.println(key+" : "+properties.getProperty(key.toString()));
                }
            }

        }
    ----------------------------

        package beans;

        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;

        public class Test {

            public static void main(String[] args) {
                // TODO Auto-generated method stub
                ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
                PropertiesBeans p = (PropertiesBeans)ap.getBean("p");
                p.getProperty();
            }

        }
    ----------------------------

 - driver.properties

    Driver = com.mysql.jdbc.Driver
    url = jdbc:mysql://localhost:3306/test
    username = root
    password = root
    ----------------------------



     <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:util="http://www.springframework.org/schema/util"
               xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

            <bean id="p" class="beans.PropertiesBeans">
                <property name="properties">
                    <util:properties location="classpath:resource/driver.properties"/>
                </property>
            </bean>

        </beans>

외부 설정 삽입에 대해서는 SpringBoot 문서에서 이 링크 https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html을 참조할 것을 권장합니다.프로퍼티 파일뿐만 아니라 YAML 파일이나 JSON 파일도 취득하는 것에 대해서도 이야기했습니다.도움이 됐어요.너도 그랬으면 좋겠다.

언급URL : https://stackoverflow.com/questions/9259819/how-to-read-values-from-properties-file

반응형