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

解决问题:我在做移动端accessToken的使用遇到一个问题,就是普通类死活注入不进去spring bean,我和同事雷杰通过各种注解,xml配置搞了好久都搞不定,这里插个眼,有空补一下spring,得深入研究一下

解决办法:后面通过一个spring工具类搞定,这里贴上代码

1、引入这个springUtil类

2、通过构造方法注入

贴上SpringUtils代码:

package com.dt.base.weixin.util;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * @Description: spring工具类 方便在非spring管理环境中获取bean
 * @author: ZhangChongHu
 * @Date: 2020/12/8 17:23
 * @Copyright: Xi'an Dian Tong Software Co., Ltd. All Rights Reserved.
 * @Version 1.0
 */
@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
 /** Spring应用上下文环境 */
 private static ConfigurableListableBeanFactory beanFactory;

 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
 {
  SpringUtils.beanFactory = beanFactory;
 }

 /**
  * 获取对象
  *
  * @param name
  * @return Object 一个以所给名字注册的bean的实例
  * @throws BeansException
  *
  */
 @SuppressWarnings("unchecked")
 public static <T> T getBean(String name) throws BeansException
 {
  return (T) beanFactory.getBean(name);
 }

 /**
  * 获取类型为requiredType的对象
  *
  * @param clz
  * @return
  * @throws BeansException
  *
  */
 public static <T> T getBean(Class<T> clz) throws BeansException
 {
  T result = (T) beanFactory.getBean(clz);
  return result;
 }

 /**
  * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
  *
  * @param name
  * @return boolean
  */
 public static boolean containsBean(String name)
 {
  return beanFactory.containsBean(name);
 }

 /**
  * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
  *
  * @param name
  * @return boolean
  * @throws NoSuchBeanDefinitionException
  *
  */
 public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
 {
  return beanFactory.isSingleton(name);
 }

 /**
  * @param name
  * @return Class 注册对象的类型
  * @throws NoSuchBeanDefinitionException
  *
  */
 public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
 {
  return beanFactory.getType(name);
 }

 /**
  * 如果给定的bean名字在bean定义中有别名,则返回这些别名
  *
  * @param name
  * @return
  * @throws NoSuchBeanDefinitionException
  *
  */
 public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
 {
  return beanFactory.getAliases(name);
 }

 /**
  * 获取aop代理对象
  *
  * @param invoker
  * @return
  */
 @SuppressWarnings("unchecked")
 public static <T> T getAopProxy(T invoker)
 {
  return (T) AopContext.currentProxy();
 }
}

贴上调用得方法:

注意:调用getValidator()方法直接返回得是 AgentCfgDao agentCfgDao ,相当于

  @Autowired
  private AgentCfgDao agentCfgDao;
/**
 * Copyright (c) 2014 - 2016 Xi'an Dian Tong Software Co., Ltd. All Rights Reserved.
 * <p>
 * This software is the confidential and proprietary information of Xi'an Dian Tong
 * Software Co., Ltd. ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with Xi'an Dian Tong Software Co., Ltd.
 */

package com.dt.base.weixin.app;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.dt.base.weixin.util.SpringUtils;
import com.dt.ncfg.dao.AgentCfgDao;
import com.dt.sys.manage.entity.DtwxAgentCfg;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import java.util.HashMap;

/**
 * 保存了 corpID + secret 和对应的 access token 。
 * key: corpID + secret
 * value: access token
 */

public class AccessTokenPool {

 protected final static Logger log = LogManager.getLogger("AccessTokenPool");

 DtwxAgentCfg dtwxAgentCfg = null;

 /**
  * 获取AgentCfgDao
  *
  * @return
  */
 protected AgentCfgDao getValidator() {
  return SpringUtils.getBean(AgentCfgDao.class);
 }

 /**
  * 根据corpID, secret 换取AccessToken
  *
  * @param corpID corpID
  * @param secret secret
  * @param type type
  * @return
  */
 public String getAccessToken(String corpID, String secret, String type) {

  //如果是企业号
  if ("QYH".equals(type)) {

   //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
   HashMap<String, Object> paramMap = new HashMap<>();
   paramMap.put("corpId", corpID);
   paramMap.put("corpSecret", secret);
   String result = HttpUtil.get(resUrl() + "/api/mobile/QYH/isExist", paramMap);
   return result;
  }
  //如果是服务号
  if ("FWH".equals(type)) {

   //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
   HashMap<String, Object> paramMap = new HashMap<>();
   paramMap.put("appId", corpID);
   paramMap.put("appSecret", secret);

   String result = HttpUtil.get(resUrl() + "/api/mobile/FWH/isExist", paramMap);
   return result;
  }
  //如果是钉钉号
  if ("DING".equals(type)) {

   //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
   HashMap<String, Object> paramMap = new HashMap<>();
   paramMap.put("appKey", corpID);
   paramMap.put("appSecret", secret);

   String result = HttpUtil.get(resUrl() + "/api/mobile/DING/isExist", paramMap);
   return result;
  }
  return null;
 }

 /**
  * 根据corpID, secret 删除旧的token
  *
  * @param corpID
  * @param secret
  * @return
  */
 public String delAccessToken(String corpID, String secret, String type) {

  if ("QYH".equals(type)) {
   //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
   HashMap<String, Object> paramMap = new HashMap<>(16);
   paramMap.put("corpId", corpID);
   paramMap.put("corpSecret", secret);
   //请求微服务接口地址
   HttpRequest.delete(resUrl() + "/api/mobile/QYH")
     .form(paramMap).execute().body();

   return null;
  }

  if ("FWH".equals(type)) {
   //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
   HashMap<String, Object> paramMap = new HashMap<>(16);
   paramMap.put("appId", corpID);
   paramMap.put("appSecret", secret);
   //请求微服务接口地址
   HttpRequest.delete(resUrl() + "/api/mobile/FWH")
     .form(paramMap).execute().body();
   return null;
  }

  if ("DING".equals(type)) {
   HashMap<String, Object> paramMap = new HashMap<>(16);
   paramMap.put("appKey", corpID);
   paramMap.put("appSecret", secret);
   //请求微服务接口地址
   HttpRequest.delete(resUrl() + "/api/mobile/DING")
     .form(paramMap).execute().body();
   return "";
  }
  return "";
 }

 /**
  * 根据corpID, secret 换取JSTicket
  *
  * @param corpID
  * @param secret
  * @return
  */
 public String getJSTicket(String corpID, String secret, String type) {

  if ("QYH".equals(type)) {
   //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
   HashMap<String, Object> paramMap = new HashMap<>(16);
   paramMap.put("corpId", corpID);
   paramMap.put("corpSecret", secret);
   //请求微服务接口地址
   String result = HttpUtil.get(resUrl() + "/api/mobile/QYH/isJSTicket", paramMap);

   return result;
  }

  if ("FWH".equals(type)) {
   //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
   HashMap<String, Object> paramMap = new HashMap<>(16);
   paramMap.put("appId", corpID);
   paramMap.put("appSecret", secret);
   //请求微服务接口地址
   String result = HttpUtil.get(resUrl() + "/api/mobile/FWH/isJSTicket", paramMap);

   return result;
  }

  if ("DING".equals(type)) {
   HashMap<String, Object> paramMap = new HashMap<>(16);
   paramMap.put("appKey", corpID);
   paramMap.put("appSecret", secret);
   //请求微服务接口地址
   String result = HttpUtil.get(resUrl() + "/api/mobile/DING/isJSTicket", paramMap);

   return result;
  }
  return "";
 }
 /**
  * 获取数据库中的url
  * @return url 地址
  */
 public String resUrl(){
  //获取url
  DtwxAgentCfg dtwxAgentCfg = new DtwxAgentCfg();
  dtwxAgentCfg.setAppType("wxInterfaceUrl");
  dtwxAgentCfg.setConfigKey("RESQUEST_ACS_TOKEN");
  DtwxAgentCfg agentCfg = getValidator().selectDataCfg(dtwxAgentCfg);
  //url=http://localhost:8080
  String url = agentCfg.getConfigValue();
  return url;
 }

}

总结:bug是搞定了,但是基础知识还要补,打卡现在是2020/12/16写得博客,那天把这里得知识补了,在回来留痕。

以上就是普通类注入不进spring bean的解决方法的详细内容,更多关于普通类注入不进spring bean的资料请关注我们其它相关文章!

(0)

相关推荐

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

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

  • spring中通过ApplicationContext getBean获取注入对象的方法实例

    用SpringContextUtil实现ApplicationContextAware package util; import java.util.Locale; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; pub

  • Springboot实现多线程注入bean的工具类操作

    场景: 使用springboot多线程,线程类无法自动注入需要的bean 解决方法: 通过工具类获取需要的bean 工具类代码: import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springfram

  • 详解Spring中bean的几种注入方式

    首先,要学习Spring中的Bean的注入方式,就要先了解什么是依赖注入.依赖注入是指:让调用类对某一接口的实现类的实现类的依赖关系由第三方注入,以此来消除调用类对某一接口实现类的依赖. Spring容器中支持的依赖注入方式主要有属性注入.构造函数注入.工厂方法注入.接下来将为大家详细介绍这三种依赖注入的方式以及它们的具体配置方法. 1.属性注入 属性注入即通过setXXX( )方法注入bean的属性值或依赖对象.由于属性注入方式具有可选择性和灵活性高的特点,因此它也是实际开发中最常用的注入方式

  • springboot2.x解决运行顺序及Bean对象注入顺序的问题

    1 前言 通过指定接口,重写指定方法,可以在Bean对应的生命周期方法中执行相应的程序 2 测试 本文将分析几个Bean对象,为它们设置优先级(通过@Order),然后再打断点调试,测试各种生命周期方法的运行的顺序 在项目当中最让人头疼的就是bean对象不被注入的问题,通过本文,你可以很好的解决这个问题. 先看看本程序使用的依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="

  • 详解Spring中接口的bean是如何注入的

    Question: 这个问题困扰了我好久,一直疑问这个接口的bean是怎么注入进去的?因为只看到使用@Service注入了实现类serviceImpl,使用时怎么能获取的接口,而且还能调用到实现类的方法,难道这个接口是在什么时候自动注入了进去,且和实现类关联上了? 接口 public interface TestService { public String test(); } 实现类impl @Service public class TestServiceImpl implements Te

  • springboot 实现bean手动注入操作

    1.springboot启动类实现接口ApplicationListener<ContextRefreshedEvent>,实现方法onApplicationEvent,初始化上下文 package test.projectTest; import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; import org.springframework.boot.SpringApplication; import or

  • 解决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

  • Spring为IOC容器注入Bean的五种方式详解

    这篇文章主要介绍了Spring为IOC容器注入Bean的五种方式详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一 @Import导入组件,id默认是组件的全类名 //类中组件统一设置.满足当前条件,这个类中配置的所有bean注册才能生效: @Conditional({WindowsCondition.class}) @Configuration @Import({Color.class,Red.class,MyImportSelector

  • 详解SpringBoot 多线程处理任务 无法@Autowired注入bean问题解决

    在多线程处理问题时,无法通过@Autowired注入bean,报空指针异常, 在线程中为了线程安全,是防注入的,如果要用到这个类,只能从bean工厂里拿个实例. 解决方法如下: 1.创建一个工具类代码: package com.hqgd.pms.common; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.spri

  • Springboot测试类没有bean注入问题解析

    这篇文章主要介绍了Springboot测试类没有bean注入问题解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 其他乱七八糟配置就不扯了,先上项目结构图 配置好参数后我再src/test/java类测试访问数据库时发现bean没有正确的注入.值得注意的是,这个项目的启动类是叫App.java 所以我们必须在这个测试类上面加上注解: @RunWith(SpringRunner.class) @SpringBootTest(classes =

  • Spring bean的实例化和IOC依赖注入详解

    前言 我们知道,IOC是Spring的核心.它来负责控制对象的生命周期和对象间的关系. 举个例子,我们如何来找对象的呢?常见的情况是,在路上要到处去看哪个MM既漂亮身材又好,符合我们的口味.就打听她们的电话号码,制造关联想办法认识她们,然后...这里省略N步,最后谈恋爱结婚. IOC在这里就像婚介所,里面有很多适婚男女的资料,如果你有需求,直接告诉它你需要个什么样的女朋友就好了.它会给我们提供一个MM,直接谈恋爱结婚,完美! 下面就来看Spring是如何生成并管理这些对象的呢? 1.方法入口 o

  • Java 如何从spring容器中获取注入的bean对象

    1.使用场景 控制层调用业务层时,控制层需要拿到业务层在spring容器中注入的对象 2.代码实现 import org.apache.struts2.ServletActionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.suppo

随机推荐