我已经收到一些关于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是null,因此我无法运行service2.formatCurrentDate,我做错了什么?
答案 0 :(得分:1)
您错过了@Autowired
对象的service2
注释。添加它,它应该工作。