2014-10-06 31 views
0

我收到豆類是如何工作的一些幫助,到目前爲止,我有一個xml:豆到豆值

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 

    <bean id= "currentDateService" class ="xx.CurrentDateServiceImpl" /> 
    <bean id= "CurrentDateServiceFormat" class ="xx.CurrentDateServiceFormatImpl"> 
    <property name="service" ref="currentDateService"/> 
    </bean> 
</beans> 

一個簡單的方法來獲得當前日期:

public class CurrentDateServiceImpl implements CurrentDateService { 
    public LocalDate getCurrentDate() { 
     return LocalDate.now() ; 

    } 
} 

,我目前正致力於在格式化當前日期我收到:

public class CurrentDateServiceFormatImpl implements CurrentDateServiceFormat{ 


    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); 

    CurrentDateService service; 

    public String formatCurrentDate(){ 
     return service.getCurrentDate().format(formatter); 
    } 

    public void setService(CurrentDateService service){ 
     this.service = service; 
    } 
} 

我的測試是:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "file:src/main/resources/META-INF/application-context.xml" }) 
public class CurrentDateServiceImplTest { 

@Autowired 
CurrentDateService service; 
CurrentDateServiceFormat service2; 


    @Test 
    public void test() { 

     LocalDate date = LocalDate.now(); 
     System.out.println(service); 
     System.out.println(service2); 
     LocalDate date2 = service.getCurrentDate(); 
     assertEquals(date, date2); 
    } 

} 

但我打印出來的service2是空的,因此即時無法運行service2.formatCurrentDate,我做錯了什麼?

+0

另請注意,如果您只是在學習Spring,您應該學習JavaConfig的處事方式 - 基於XML的配置僅用於遺留目的,不會用於這個世界...... – 2014-10-06 07:31:42

+0

是否有任何優秀的教程可以提供建議學習JavaConfig的方式? – Monty 2014-10-06 07:35:32

+0

最簡單的出發點之一是[new Spring Boot](http://spring.io/guides/gs/spring-boot/)自動引導程序。否則,[參考文檔]中有大量信息(http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch03.html)。 – 2014-10-06 07:37:33

回答

1

您錯過了service2對象的@Autowired註釋。添加它,它應該工作。