나는 봄을 사용하고 있습니다. 속성 파일에서 값을 읽어야합니다. 외부 특성 파일이 아닌 내부 특성 파일입니다. 속성 파일은 다음과 같습니다.
some.properties ---file name. values are below.
abc = abc
def = dsd
ghi = weds
jil = sdd
전통적인 방식이 아닌 속성 파일에서 해당 값을 읽어야합니다. 그것을 달성하는 방법? 스프링 3.0에 대한 최신 접근 방식이 있습니까?
답변
컨텍스트에서 PropertyPlaceholder를 구성하십시오.
<context:property-placeholder location="classpath*:my.properties"/>
그런 다음 Bean의 특성을 참조하십시오.
@Component
class MyClass {
@Value("${my.property.name}")
private String[] myValues;
}
편집 : 쉼표로 구분 된 여러 값으로 속성을 구문 분석하도록 코드를 업데이트했습니다.
my.property.name=aaa,bbb,ccc
그래도 작동하지 않으면 특성이있는 Bean을 정의하고 수동으로 삽입하고 처리 할 수 있습니다.
<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
}
}
답변
이를 달성하는 데는 여러 가지 방법이 있습니다. 다음은 봄에 일반적으로 사용되는 몇 가지 방법입니다.
-
PropertyPlaceholderConfigurer 사용
-
PropertySource 사용
-
ResourceBundleMessageSource 사용
-
PropertiesFactoryBean 사용
그리고 더 많은……………………
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
, 나는 좋은 발견 링크 버전 compatibility-을 이해하기를
@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
모든 BeanFactoryPostProcessor Bean은 static , modifier 로 선언해야합니다.
@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;
}
}
답변
애플리케이션 컨텍스트에 PropertyPlaceholderConfigurer Bean을 넣고 위치 특성을 설정해야합니다.
자세한 내용은 여기를 참조하십시오 : http://www.zparacha.com/how-to-read-properties-file-in-spring/
이 작업을 수행하려면 속성 파일을 약간 수정해야 할 수도 있습니다.
도움이 되길 바랍니다.
답변
다른 방법은 ResourceBundle을 사용하는 것 입니다. 기본적으로 ‘.properties’없이 이름을 사용하여 번들을 얻습니다.
private static final ResourceBundle resource = ResourceBundle.getBundle("config");
그리고 이것을 사용하여 모든 가치를 회복하십시오.
private final String prop = resource.getString("propName");
![](http://daplus.net/wp-content/uploads/2023/04/coupang_part-e1630022808943-2.png)