繁体   English   中英

豆到豆值

[英]Bean to bean values

我已经收到有关bean如何工作的帮助,到目前为止,我有一个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,我在做什么错?

您会错过service2对象的@Autowired批注。 添加它,它应该可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM