SpringBoot解决@Component无法注入其他Bean的问题

目录
  • SpringBoot @Component无法注入其他Bean
    • 一、现象
    • 二、解决
    • 三、代码如下
  • @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声明 进行自动注入失效

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 解决Spring Boot 多模块注入访问不到jar包中的Bean问题

    情景描述 一个聚合项目spring-security-tutorial,其中包括4个module,pom如下所示: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://mav

  • 解决springboot无法注入JpaRepository的问题

    使用内置服务器启动springboot项目时,会从@SpringBootApplication修饰类所在的包开始,加载当前包和所有子包下的类,将由@Component @Repository @Service @Controller修饰的类交由spring进行管理. package com.facade; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure

  • spring boot拦截器注入不了java bean的原因

    一.如何实现拦截器 在Spring Boot项目中,拦截器经常被用来做登陆验证,日志记录等操作.拦截器是Spring提供的,所以可以将拦截器注成bean,由IOC容器来管理.实现拦截器的方式很简单,主要由以下两个步骤: 自定义拦截器类实现HandlerInterceptor接口 自定义WebMvc配置类实现WebMvcConfigurer接口,添加自定义拦截器类 简要实现代码如下: 自定义拦截器 LoginInterceptor: public class LoginInterceptor im

  • 普通类注入不进spring bean的解决方法

    解决问题:我在做移动端accessToken的使用遇到一个问题,就是普通类死活注入不进去spring bean,我和同事雷杰通过各种注解,xml配置搞了好久都搞不定,这里插个眼,有空补一下spring,得深入研究一下 解决办法:后面通过一个spring工具类搞定,这里贴上代码 1.引入这个springUtil类 2.通过构造方法注入 贴上SpringUtils代码: package com.dt.base.weixin.util; import org.springframework.aop.f

  • SpringBoot解决@Component无法注入其他Bean的问题

    目录 SpringBoot @Component无法注入其他Bean 一.现象 二.解决 三.代码如下 @Component注解自动注入失效问题 SpringBoot @Component无法注入其他Bean 一.现象 在SpringBoot新new一个普通类,习惯性添加@Component让Spring扫描. 在@Component修饰的类里注入了其他Bean,运行时提示注入的为null 但这个Bean可以在控制层被引入,在普通类就不行. 二.解决 找了些资料,最后也没解决注入的问题. 最后的

  • 详解SpringBoot 解决拦截器注入Service为空问题

    一.自定义拦截器实现 HandlerInterceptor 接口 /** * * Created by zhh on 2018/04/20. */ public class MyInterceptor implements HandlerInterceptor { @Autowired private NetworkProxyInfoService networkProxyInfoService; @Override public void afterCompletion(HttpServlet

  • springboot拦截器无法注入redisTemplate的解决方法

    在工作中我们经常需要做登录拦截验证或者其他拦截认证功能,基于springboot项目下我们很容易想到结合redis做的分布式拦截,把用户登录或者需要验证的信息放到redis里面.但是在写拦截器的时候发现redisTemplate一直无法注入进来,最后查资料才发现springboot拦截器是在Bean实例化之前执行的,所以Bean实例无法注入. 先看下问题,新建一个拦截器,然后注入redisTemplate /** * @author: lockie * @Date: 2019/8/13 16:1

  • Springboot @WebFilter无法注入其他Bean的示例问题

    示例问题代码: @WebFilter(filterName = "authorizeFilter", urlPatterns = {"*.htm", "*.html"}, asyncSupported = true) public class AuthorizeFilter implements Filter { @Autowired private OtherBean otherBean; @Override public void init(

  • 关于SpringBoot获取IOC容器中注入的Bean(推荐)

    一: 注入一个TestUtils类 package com.shop.sell.Utils; import com.shop.sell.dto.CartDTO; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestUtils { @Bean(name="test

  • springboot如何读取自定义properties并注入到bean中

    目录 读取自定义properties注入到bean springboot启动日志如下 springboot bean实例化和属性注入过程 springboot版本(2.0.4 RELEASE) Bean的实例化 Bean的属性注入 读取自定义properties注入到bean 在使用springboot项目时,可使用@value的方式直接读取application.properties中的文件,但有时我们需要配置自定义的properties,下面方法将在springboot启动时利用filein

  • Springboot 在普通类型注入Service或mapper

    目录 Springboot 在普通类型注入Service或mapper 1.由于之前都是通过controller调用service层来实现访问 2.在拿到数据之后,掉service时出现空指针 springboot 普通类怎么使用注入 Springboot 在普通类型注入Service或mapper 最近遇到一个难题(大佬可能感觉这太简单了把),对于我这样的小白来说,确实有些头疼. 接下来说一下我遇到的问题,在spring boot中创建了一个UDP客户端,用于监听UDP服务端发送到数据.在实现

  • SpringBoot下的值注入(推荐)

    在我们实际开发项目中,经常会遇到一些常量的配置,比如url,暂时不会改变的字段参数,这个时候我们最好是不要直接写死在代码里的,因为这样编写的程序,应用扩展性太差了,我们可以直接写在配置文件中然后通过配置文件读取该字段的值,这样的话以后需要更改,也不用在重新修改代码,好处不言而知. 一,字段直接注入 @Value("${example.url}") private String url; 这样直接在配置文件里写url值即可(application.properties|applicati

  • SpringBoot解决ajax跨域问题的方法

    SpringBoot解决ajax跨域,供大家参考,具体内容如下 一.第一种方式 1.编写一个支持跨域请求的 Configuration import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.anno

  • Springboot解决ajax+自定义headers的跨域请求问题

    1.什么是跨域 由于浏览器同源策略(同源策略,它是由Netscape提出的一个著名的安全策略.现在所有支持JavaScript 的浏览器都会使用这个策略.所谓同源是指,域名,协议,端口相同.),凡是发送请求url的协议.域名.端口三者之间任意一与当前页面地址不同即为跨域. 具体可以查看下表: 2.springboot如何解决跨域问题 1.普通跨域请求解决方案: ①请求接口添加注解@CrossOrigin(origins = "http://127.0.0.1:8020", maxAge

随机推荐