当前位置:首页 > 通信资讯 > 正文

springboot @component无法注入(springboot component注解)

SpringBoot @Component无法注入其他Bean

一、现象

在SpringBoot新new一个普通类,习惯性添加@Component让Spring扫描。

在@Component修饰的类里注入了其他Bean,运行时提示注入的为null

但这个Bean可以在控制层被引入,在普通类就不行。

二、解决

找了些资料,最后也没解决注入的问题。

最后的方案就是去掉@Component注解,在new这个普通类时从Spring上下文实例中取出这个Bean赋给成员变量使用。

弊端:这个类非单例

三、代码如下

ApplicationContextProvider

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextProvider implements ApplicationContextAware { /** * 上下文对象实例 */ private static ApplicationContext applicationContext; @SuppressWarnings("static-access") @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /** * 获取applicationContext * * @return */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 通过name获取 Bean. * * @param name * @return */ public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 通过class获取Bean. * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }

IdentityCheckUtil

import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import org.apache.log4j.Logger; public class IdentityCheckUtil { private Logger logger = Logger.getLogger(IdentityCheckUtil.class); private UserMapper userMapper; public IdentityCheckUtil() { this.userMapper = ApplicationContextProvider.getBean(UserMapper.class); } public boolean allowedPass(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) { System.out.println(userMapper); } }

@Component注解自动注入失效问题

使用@Component声明 进行自动注入失效

springboot @component无法注入(springboot component注解)

@Component,在默认情况下只能扫描与控制器在同一个包下以及其子包下的@Component注解,以及能将指定注解的类自动注册为Bean的@Service@Controller和@ Repository,将接口与对应实现类放在了与控制器所在包的同一级目录下,这样的注解自然是无法被识别的。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/wkh___/article/details/87876442

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。