zoukankan      html  css  js  c++  java
  • springboot 静态方法注入bean、使用@value给static变量赋值

    首先新建你的方法类:DemoUtil

    头部加注解:@Component

    @Component
    public class DemoUtil {
    }

    新增静态变量:

    static DemoService demoService;

    新增@Autowired的bean对象

    @Autowired
    DemoService demoServiceMapping;

    注意这时候还是不能注入

    新增@PostConstruct注解方法

    @PostConstruct
    public void init() {
        demoService = demoServiceMapping; 
    }

     当然还需要注意的就是启动类的扫描范围:

    不同包下可在启动类加上@ComponentScan配置扫描范围

    properties 属性引入

    假若在properties文件中配置如下属性:project.author

    之前有写到用@value

    那么在静态方法中怎么引入呢,直接@value是不可以的,一下介绍两种方法

    第一种:如上文注入bean方式,在@PostConstruct方法中配置使用

    第二种:

    public static String springProfilesActive;
    
    @Value(value = "${spring.profiles.active}")
    public void setSpringProfilesActive(String springProfilesActive) {
        SystemConfig.springProfilesActive = springProfilesActive;
    }

    使用set方法赋值,set方法static去掉,这种方法也必须注意启动类的扫描范围。

  • 相关阅读:
    scala-隐式转换
    scala-泛型
    scala-模式匹配
    scala-LinkedList
    scala-高阶函数
    scala-数组/列表
    scala-map
    scala语法
    机器学习笔记
    Day 1 下午
  • 原文地址:https://www.cnblogs.com/skyLogin/p/9233119.html
Copyright © 2011-2022 走看看