赞
踩
目录
Controller 层方法为 static 静态,引入 Service 层时使用 @Autowired 注解自动装配,Controller层方法里无法调用Service层,于是加static修饰Service层的注入
调用Service层进行数据库操作时,注入的Service层报空指针异常( NullPointerException )

静态变量需要在实例化后才能使用,而静态变量没有实例化时为null,导致空指针异常。
static 与 @Autowired 注解冲突,导致自动装配拉胯
- <!--工具集-->
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.8.12</version>
- </dependency>
根据类装配 Bean ,或其它方式
SpringUtil.getBean(Service.class);
- package com.lesliecheung.util.spring;
-
- import org.springframework.beans.BeansException;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
- import org.springframework.stereotype.Component;
-
- /**
- * @Package_Name com.lesliecheung.util.spring
- * @Author yi.li/Leslie Lee
- * @TIME 11:57
- * @Version 1.0
- * spring工具类
- */
- @Component
- public class SpringUtil implements ApplicationContextAware {
-
- private static ApplicationContext applicationContext;
-
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- if(SpringUtil.applicationContext == null) {
- SpringUtil.applicationContext = applicationContext;
- }
- }
-
- //获取applicationContext
- public static ApplicationContext getApplicationContext() {
- return applicationContext;
- }
-
- //通过name获取 Bean.
- public static Object getBean(String name){
- return getApplicationContext().getBean(name);
- }
-
- //通过class获取Bean.
- public static <T> T getBean(Class<T> clazz){
- return getApplicationContext().getBean(clazz);
- }
-
- //通过name,以及Clazz返回指定的Bean
- public static <T> T getBean(String name,Class<T> clazz){
- return getApplicationContext().getBean(name, clazz);
- }
-
- }

使用 static 静态块初始化
Cheung Kwok Wing 随笔
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。