I have received some help on how beans work, so far i have an 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>
A simple method to obtain the current date:
public class CurrentDateServiceImpl implements CurrentDateService {
public LocalDate getCurrentDate() {
return LocalDate.now() ;
}
}
And i am currently working on formating the current date i receive:
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;
}
}
My test is:
@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);
}
}
But the service2 i get printed out is null, thus im unable to run service2.formatCurrentDate, what am i doing wrong?
You miss the @Autowired
annotation for the service2
object. Add it and it should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.