2017-12-15 4 views
1

"필요한 경우 중복으로 표시하되 주석에는 솔루션 링크를 남겨 두십시오."
클래스 "Assignment22.Player.java"중 5 개의 인스턴스를 만들고 속성을 주입해야합니다. XML 파일 자체에 하드 코딩하여 인스턴스에 속성을 삽입 할 수 있습니다. 하지만 XML 파일로 이동하여 나중에 "변경"요구 사항이있을 경우 속성을 변경하지 않아도되도록하고 싶습니다. 이는 하나 이상의 특성 파일을 사용하여 달성 할 수 있습니다.
다음은 내가 시도한 것입니다.
5 가지 인스턴스에 대해 5 개의 속성 파일을 만들었습니다. 그러나 클래스는 동일하므로 모든 객체의 속성 이름이 동일합니다. 그래서 겉으로보기에는, 나는 이런 식으로 속성 파일을 사용할 수 없다. 나는 동적으로 (동일한 속성의 이름이) 동일한 참조 유형의 다른 콩에 다른 속성 값을 삽입 할 수있는 방법을 알 필요가
같은 클래스의 다른 인스턴스에 속성 삽입하기 (스프링 프레임 워크)

<!-- country bean --> 
    <bean id = "country1" class="Assignmetn22.Country"> 
    <property name= "countryId" value="${countryId}"></property> 
    <property name= "countryName" value="${countryName}"></property> 
    </bean> 
    <bean id = "country2" class="Assignmetn22.Country"> 
    <!-- since the properties' names are same there won't any effect if assign them different values 
    and use them for different beans. 
    --> 
</bean> 


<bean id = "player1" class="Assignment22.Player"> 
    <property name="playerId" value="${playerId}"></property> 
    <property name="playerName" value="${playrName}"></property> 
    <property name="country" ref="country1"></property> 
</bean> 

<bean id = "player2" class="Assignment22.Player"> 
    <!-- same properties' names for other bean --> 
    <!-- since the properties' names are same there won't any effect if assign them different values 
    and use them for different beans. 
    --> 
    <!-- <property name="playerId" value="${playerId}"></property> 
      <property name="playerName" value="${playrName}"></property> 
      <property name="country" ref="country2"></property> 
    --> 
    </bean> 


    <!--loading the properties file--> 
    <bean id= "placeholderConfig1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:p1.properties"></property> 
    </bean> 
    <bean id= "placeholderConfig2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:p2.properties"></property> 
    </bean> 
    <bean id= "placeholderConfig3" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:p3.properties"></property> 
    </bean> 
    <bean id= "placeholderConfig4" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:p4.properties"></property> 
</bean> 
<bean id= "placeholderConfig5" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:p5.properties"></property> 
    </bean> 

:
는 여기에 내가 시도 XML 코드입니다. XML을 사용하여 코드를 하드 코딩하고 싶지 않습니다. 자바 방식이 있습니까? 설명 해주십시오.

답변

2

빈 내부에 Spring @ Value 주석을 사용할 수 있습니다. 새 인스턴스가 생성되면 Spring에서 속성 값을 채 웁니다.

public class Player 
{ 
    @Value("${playerName}") 
    private String playerName; 
} 

당신이 당신의 플레이어-콩으로 속성과 와이어를 보유하고 빈을 생성, 주석을 사용하는 XML 구성을 고수하지하려면

.

playerProperties에서 scope = "prototype"을 사용하면 모든 플레이어에 대해 하나의 인스턴스가 만들어집니다. 이렇게하면 플레이어는 해당 속성을 공유하지 않습니다.

Player 인스턴스가 PlayerProperties Bean을 공유하도록하려면 scope = "singleton"(기본값)을 사용하십시오.

public class Player 
{ 
    PlayerProperties props; 
} 

public class PlayerProperties 
{ 
    String playerName; 
    //getter,setter,... 
} 


<bean id = "player2" class="Player"> 
    <property name="props" ref="playerProperties"></property> 
    ... 
</bean> 


<bean id = "playerProperties" class="PlayerProperties" scope="prototype"> 
    <property name="playerName" value="${playrName}"></property> 
    ... 
</bean> 
+0

주어진 속성 파일에는 고유 한 ** 속성 = 값 ** 쌍이 있습니다. 또한 주어진 클래스에 대해 5 개의 객체는 동일한 속성 이름 (인스턴스 변수)을 갖습니다. 예 - 'ClassObj obj1, obj2; obj1.name = "TomB"; obj2.name = "zerobyzero" '. 문제는 obj1과 obj2의 ** name ** 속성에 별도로 값을 주입하는 방법입니다. 나는 XML을 사용하여 하드 코딩을하고 싶지 않다. 나에게 몇 가지 자바 방법이나 속성 파일을 사용하는 것이 좋습니다. – zerobyzero

0

Application 클래스 :

@ComponentScan 
@EnableAutoConfiguration 
@EnableConfigurationProperties 
@EnableAsync 
@EnableScheduling 
@Configuration 
@SpringBootApplication 

//use players.properties 
@PropertySource("classpath:players.properties") 
public class InstancePropsApp { 

    public static void main(String[] args) { 
     SpringApplication.run(InstancePropsApp.class, args); 
    } 

    //Create 3 Player Beans (could be done in XML-Config, too) 
    @Bean Player player1() {return new Player();} 
    @Bean Player player2() {return new Player();} 
    @Bean Player player3() {return new Player();} 

    @PostConstruct 
    public void init() 
    { 
     //Output values after init. 
     player1().echoName(); 
     player2().echoName(); 
     player3().echoName(); 
    } 

} 

플레이어 클래스

@Component 
@Scope("prototype") 
//Make bean aware of it's name to use bean name as property prefix 
public class Player implements BeanNameAware { 

    @Autowired 
    private ConfigurableEnvironment environment; 

    private String name; 


    public void setName(String name) { 
     this.name = name; 
    } 

    private String beanName; 

    @PostConstruct 
    public void init() { 
     //init this beans properties from "beanName.xxx" values. e.g. 
     //player1.name and player2.name ans so on 
     new RelaxedDataBinder(this, beanName).bind(new 
     PropertySourcesPropertyValues(environment.getPropertySources())); 
    } 

    //We use our very own bean name as prefix to load properties per 
    //prototype instance 
    public void setBeanName(String beanName) { 
     this.beanName = beanName; 
    } 

    public void echoName() 
    { 
     System.out.println(beanName + " : " + name); 
    } 

} 

players.properties :

player1.name=max 
player2.name=theo 
player3.name=karren 

,536를 인쇄합니다
player1 : max 
player2 : theo 
player3 : karren