我正在使用Spring 4.3.0 annotation with java config
,我制作了一个小型的Spring MVC Web项目。我试图在@Controller中使用@Autowire
注释,它完全正常。但这在@Service或@Repository
@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 类
@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 类
@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();
}
}
另外如果我可以在@Controller
中没有 AnnotationConfigApplicationContext 来初始化bean,那么我们真的需要AnnotationConfigApplicationContext
吗?
先谢谢
修改
这是一个非常天真的问题,所以如果有人像我一样理解,这就是答案:
自动装配在@Controller中工作但在@Service中没有,因为我使用new
手动初始化服务对象,因此自动初始化不能在@Service类中工作
关于ApplicationAnnotation
我们不需要,因为bean在启动时通过组件扫描初始化,这是整个弹簧点