解决springboot关于@Autowired注入为null的问题

有些类不是controller在使用autowired注入的service类显示为null

  • 完美解决
  • 没有new

  • ps 使用@ConfigurationProperties(prefix = “xxxx”)时,在工具类例如 UserUtils 类封装方法,在RestController 类中 调用

//示例
@Component
public class DemoUtil{
    @Autowired
    private DemoPro demoPro; //@ConfigurationProperties(prefix = "xxxx") 读取Bean类

	public demo getDemo(){
	 String demothree = "123"
	  return demoTwoFun(demoPro.getBase64, demothree)
	}
 }
//错误示例
@RestController
public class Demo{
	@GetMapping("/getDemo")
	public demo getDemo(){
	  return new DemoUtil().getDemo()
	}
}
//——————————————————————————————分割线————————————————————————————————
//成功读取示例
@RestController
public class Demo{
	@Autowired
	private DemoUtil demoUtil;
	@GetMapping("/getDemo")
	public demo getDemo(){
	  return demoUtil.getDemo()
	}
}
//*******************工具 类*******************
@Component
public class DemoUtil{
    @Autowired
    private DemoMapper demoMpper;

	public demo getDemo(){
	  QueryWarpper query = new QueryWarpper<>();
	  query.eq("id",1)
	  return demoMpper.selectOne(query)
	}
 }
//*******************controller 类*******************

@RestController
public class Demo{
	@Autowired
	private DemoUtil demoUtil;
	@RequestMapping(value = "/getDemo", method = RequestMethod.POST)
	public demo getDemo(){
	  return demoUtil.getDemo()
	}
}
  • 第一种解决方式
@Component
public class ProductInstLogic {
    @Autowired
    private InstImpl instImpl;
    
    private static ProductInstLogic pil ;
    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        pil = this;
        pil.InstImpl = this.instImpl;
        pil.ProductInstImpl = this.ProductInstImpl;
        // 初使化时将已静态化的testService实例化
    }
 }
  • 第二种解决方式
@Component
public class ProductInstLogic {
    @Autowired
    // @Resource
    private InstMapper InstMapper;
}
@Component
public class TimingAuto {
    @Autowired
    private ProductInstLogic productInstLogic;
    
    @Scheduled(cron = "0/10 * * * * ?") //10秒执行一次
    public void productInstSocket() {
       	productInstLogic.ProductInstAll();
    }
    
}
@RestController
public class ProductInstController {
    @Autowired
    private ProductInstLogic productInstLogic;
}

你可能感兴趣的:(java)