工具类注入需要的service

本文介绍了一个Spring Boot应用如何通过整合Redis来缓存登录员工的详细信息,包括使用@Component注解使类被Spring扫描,@Autowired注入依赖服务,以及@PostConstruct注解初始化静态对象的方法。
/**
 *  从redis获取信息
 * @author yy
 *
 */

@Component//关键一:添加此注解才能被spring扫描到
public class CacheUtil {
    
    private static Logger logger = LoggerFactory.getLogger(CacheUtil.class);
    
    @Autowired
    private JJWTUtils jwt;  //关键二:添加需要的服务类
    public static CacheUtil cacheUtil; //关键三:声明一个当前类的静态对象
    
    
    @PostConstruct  //关键四:通过@PostConstruct注解实现注入
    public void init() {
        cacheUtil = this;
        //cacheUtil.jwtUtils =  this.jwtUtils;
    }
    
    
    /**
     * 从Redis中获取登录的员工详细信息
     * @Title: getRedisEmp
     * @Description:
     * @return
     * @return EmployeVo
     * @author yy  2019-6-26 16:11:31
     */
    @SuppressWarnings("unused")
    private static EmployeVo getRedisEmp(HttpServletRequest request) {
        EmployeVo emp = null;
        JwtBodyBean jwtBody = cacheUtil.jwt.getJwtBody(request);
        if (jwtBody != null) {
            Long uid = jwtBody.getUid();
            Object jsonObj = cacheUtil.jwt.redisService.get(String.valueOf(uid));
            if (jsonObj != null) {
                JSONObject json = JSONObject.parseObject(jsonObj.toString());
                emp = new EmployeVo();
                try {
                    emp.setEmId(json.getString("emId"));
                    emp.setDepartmentId(json.getString("departmentId"));
                    emp.setEmAccount(json.getString("emAccount"));
                    emp.setEmPassword(json.getString("emPassword"));
                    emp.setUserName(json.getString("userName"));
                    emp.setEmPhone(json.getString("emPhone"));
                    emp.setSeatId(json.getString("seatId"));
                    emp.setEmLevel(json.getIntValue("emLevel"));
                    emp.setCrmUserId(json.getString("crmUserId"));
                    emp.setAcAccount(json.getString("acAccount"));
                    emp.setAcPassword(json.getString("password"));
                    emp.setBs(json.getIntValue("bs"));
                    emp.setTs(json.getString("ts"));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("从redis查询员工信息异常!", e.toString());
                }
            }
        }
        return emp;
    }

}

 

转载自 https://blog.youkuaiyun.com/loveer0/article/details/83716040

 

转载于:https://www.cnblogs.com/yangyang2018/p/11091349.html

### 如何在 Spring 工具类注入 Service 组件 为了确保工具类能够正常访问 `Service` 组件而不引发空指针异常,可以采用多种策略来实现依赖注入。以下是几种推荐的做法: #### 使用 ApplicationContext 获取 Bean 实例 通过获取当前应用程序上下文中的 `ApplicationContext` 来手动查找并实例化所需的 `Bean` 对象。 ```java import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class MyUtils implements ApplicationContextAware { private static ApplicationContext context; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static SomeService getSomeService() { return (SomeService) context.getBean("someServiceImpl"); } } ``` 这种方式允许静态方法内部调用其他服务层逻辑而不会遇到未初始化的问题[^1]。 #### 利用 @Component 和非静态成员变量 如果不需要保持工具函数为纯静态形式,那么最简单的方式就是让工具类本身成为容器管理的一个组件,并像平常一样声明属性级别的自动装配字段即可。 ```java @Component public class AnotherUtil { @Autowired private transient SomeService someService; // 注意这里使用transient修饰符防止序列化问题 public String doSomethingUseful(){ return this.someService.performAction(); } } ``` 此模式下所有的依赖关系都由框架负责处理,开发者无需关心具体的创建过程[^3]。 #### 结合 Factory Method 设计模式 对于那些确实需要保留某些程度上的无状态特性的辅助功能模块来说,工厂方法提供了一种折衷的选择——既维持了外部可见性上的一致性又解决了内部协作对象缺失难题。 ```java @Service class UtilFactory{ @Autowired private final Map<String,Object> serviceBeans; Object createUtility(String serviceName){ return serviceBeans.get(serviceName); } } // Usage example within another component or controller @Autowired private UtilFactory utilFactory; @RequestMapping("/example") String handleRequest(){ var myTool=(MyToolInterface)utilFactory.createUtility("myToolImpl"); ... } ``` 这种方法利用了Spring内置的支持按名称检索特定类型的bean映射表结构特性,从而实现了灵活的服务定位机制[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值