Java开发工作问题整理与记录

1、为什么@Autowired不能注入static成员属性

复制代码
扫描Class类需要注入的元数据的时候,直接选择忽略掉了static成员(包括属性和方法)
Spring 依赖注入是依赖set方法, set方法是普通的对象方法,static变量是类的属性
复制代码
AutowiredAnnotationBeanPostProcessor:
 
// 构建@Autowired注入元数据方法
// 简单的说就是找到该Class类下有哪些是需要做依赖注入的
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
    ...
    // 循环递归,因为父类的也要管上
    do {
        // 遍历所有的字段(包括静态字段)
        ReflectionUtils.doWithLocalFields(targetClass, field -> {
            if (Modifier.isStatic(field.getModifiers())) {
                logger.info("Autowired annotation is not supported on static fields: " + field);
            }
            return;
            ...
        });
        // 遍历所有的方法(包括静态方法)
        ReflectionUtils.doWithLocalMethods(targetClass, method -> {
            if (Modifier.isStatic(method.getModifiers())) {
                logger.info("Autowired annotation is not supported on static methods: " + method);
            }
            return;
            ...
        });
        ...
        targetClass = targetClass.getSuperclass();
    } while (targetClass != null && targetClass != Object.class);
    ...
}

2、static方法里用@Autowire或者@Resource注入的属性

首先 类加@Component注解,使当前类成为bean

然后 定义statis类成员

然后 创建 init()方法,用@PostConstruct注解修饰

最后init()方法中,把需要加载的类复制给static类

复制代码
@Component
public class DemoCode {

    @Autowired
    private DemoService demoService;

    public static DemoService demoServiceNew;

    /**
     * 解决 static方法调用  注入的service为null
     */
    @PostConstruct
    public void init(){
        demoServiceNew = demoService;
    }
 }

3、处理string类型的json串中的反斜杠

导入commons-lang3的jar包

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

<version>3.8.1</version>

</dependency>

复制代码
public static void main(String[] args) {
        String s="{\\\"displayName\\\":\\\"\\\",\\\"id\\\":1401524465412907010,\\\"name\\\":\\\"名称\\\",\\\"source\\\":\\\"\\\",\\\"type\\\":\\\"text\\\",\\\"value\\\":\\\"红细胞计数\\\"}";
        String tmp = StringEscapeUtils.unescapeJava(s);
        System.out.println(tmp);
    }

//输出结果
//{"displayName":"","id":1401524465412907010,"name":"名称","source":"","type":"text","value":"红细胞计数"}

4、对象拷贝的方法

import org.springframework.beans.BeanUtils;

BeanUtils.copyProperties(原始对象, 新对象);

相关推荐
gadiaola27 分钟前
【JVM】Java虚拟机(二)——垃圾回收
java·jvm
крон2 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan3 小时前
c++ 单例模式
开发语言·c++·单例模式
coderSong25683 小时前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
Mr_Air_Boy4 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
曹勖之4 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?4 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头5 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#