I've worked with legacy Spring in the past. We defined our beans via xml configuration and manually wired them. My team is finally making a concerted effort to update to annotations and use Spring Boot instead of the 'traditional' approach with Spring MVC.
With that said, I cannot figure out how the heck I retrieve a bean in Boot. In legacy, Spring would either use constructor/setter injection (depending on our configuration), or we could directly call a bean with context.getBean("myBeanID");
However, it does not appear to be the case anymore.
I put together a small test case to try and get this working in the below code:
package com.ots;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class GriefUIApplication{
public static void main(String[] args) {
SpringApplication.run(GriefUIApplication.class, args);
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.addAnnotatedClass(GriefRecord.class).addAnnotatedClass(RecordId.class)
.addAnnotatedClass(CrossReferenceRecord.class)
.buildSessionFactory();
Statics.setSessionFactory(factory);
TennisCoach tCoach = new TennisCoach();
tCoach.getCoach();
}
}
interface Coach{
public String workout();
}
@Service
class TennisCoach implements Coach{
private Coach soccerCoach;
@Autowired
private ApplicationContext context;
public TennisCoach() {
}
public Coach getCoach() {
System.out.println(context + " IS THE VALUE OF THE CONTEXT OBJECT");
soccerCoach = (SoccerCoach)context.getBean("soccerCoach");
System.out.println(soccerCoach.getClass());
return soccerCoach;
}
@Override
public String workout() {
String practice = "practice your backhand!";
System.out.println(practice);
return practice;
}
}
@Service
class SoccerCoach implements Coach{
public SoccerCoach() {
}
@Override
public String workout() {
String practice = "practice your footwork!";
System.out.println(practice);
return practice;
}
}
@RestController
class MyController{
@GetMapping("/")
public String sayHello() {
return "Time on server is: " + new java.util.Date();
}
}
I tried autowiring the ApplicationContext object into the TennisCoach class. When I run this, that object is null.
How do we retrieve beans in Boot?