springboot通过new关键字创建的类中 @Resource 注解的对象没有成功注入,无法调用service层接口

Springboot项目中 new 创建的对象中无法使用@Resource 或@Autowired 注解实例化service层注入

那么如何引用呢,web启动类中注入 service 对象 设置为static new创建的对象 类中引用,测试不可实现,以为静态变量 不能用@Resource 或@Autowired 注入,所以可通过以下方式实现,将注入的方法正常注入fService对象

 @Resource
    public FService fService;

在重新声明一个static 的方法对象

public static FService sFService;

  通过

@PostConstruct
    public void init() {
        sFService = this.fService;
    }

实例化静态化对象

需要new创建的类中就可以 通过类名.对象名 获取操作数据库的接口了,测试可以实现数据库的读写操作

@Slf4j
@Component
@Order(value = 1)
public class MyServletContextListener implements ApplicationRunner {

    @Resource
    public FService fService;
    //实际需要上的静态属性

    public static FService sFService;

    @PostConstruct
    public void init() {
        sFService = this.fService;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("应用程序启动");
        
    }

}

猜你喜欢

转载自blog.csdn.net/wuyufeng891021/article/details/84614123