I am using Spring 4.3.0 annotation with java config
and i made a small Spring MVC web project . I was trying to use the @Autowire
annotation in my @Controller which works perfectly fine . But this dosen't work in @Service or @Repository
Code for @Controller :
@Controller
public class LoginController
{
@Autowired
private EmployeeInfo employeeInfo; //works perfectly fine
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
private AuthenticationService authenticationService = AuthenticationService.getAuthenticationInstance();
@RequestMapping(value = "/login.jsp" , method = RequestMethod.GET)
public ModelAndView userLoginPage(){
return new ModelAndView("Login");
}
}
@Service class
@Service
public class AuthenticationService
{
@Autowired
private EmployeeInfo employeeInfo; // this gives NULL
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationService.class);
private static AuthenticationService authenticationService;
LoginDao loginDao = LoginDao.getLoginInstance();
private boolean firstTimeLogin = false;
public static AuthenticationService getAuthenticationInstance(){
if(authenticationService == null)
authenticationService = new AuthenticationService();
return authenticationService;
}
}
@Configuration class
@EnableWebMvc
@Configuration
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = "programs.examples")
public class AppConfig
{
@Bean
public ViewResolver jspViewResolver() {
UrlBasedViewResolver resolver = new ChainableUrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setOrder(0);
return resolver;
}
@Bean
public ViewResolver jspViewResolver2() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view2/");
resolver.setSuffix(".jsp");
resolver.setOrder(1);
return resolver;
}
@Bean // @Component is used with EmployeeInfo
public EmployeeInfo employeeInfo(){
return new EmployeeInfo();
}
}
Also if i can initialize the bean without AnnotationConfigApplicationContext in @Controller
, then do we really need AnnotationConfigApplicationContext
?
Thanks in Advance
EDIT
This was a very naive question , so if anyone dosen't understand like me , here is the answer :
Autowiring was working in @Controller but not in @Service , because i initialized service object manually with new
, so automatic initialization won't work in @Service class
Regarding ApplicationAnnotation
we don't need that since beans are initialized at startup via component scan which is the whole point of spring