我已经收到有关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,我在做什么错?
最佳答案
您错过了@Autowired
对象的service2
批注。添加它,它应该可以工作。