springboot依赖注入的三种方式(非autowired)

  • Post author:
  • Post category:其他


Springboot会自动加载resources文件下面的application.yml或者application.properties配置文件,因为yml格式可以替代xml格式,功能properties更强大,所以一般都使用yml格式进行书写。

1.对于yml中定义了的bean,可以使用 @value(“${对象}”) 进行注入。 如果是对象变量,可以直接在变量上使用value注解进行注入。如果是下图这样的静态变量,就需要在set方法上使用value注解。注意:必须是在Spring容器中的对象才能够进行注入,即需要加@Component注解。

@Component
public class Student {
    public static String name;
    public static int age;

    @Value("${student.name}")
    public void setName(String name){
        Student.name = name;
    }

    @Value("${student.age}")
    public void setAge(int age){
        Student.age = age;
    }
}


student: 
    name: '小明'
    age: 15

2.也可以在需要使用Spring容器值的类上加@Component和@ConfigurationProperties(prefix=”对象名”),将application.yml中配置的对象student(IOC容器中的值)注入进来。(必须是IOC容器中的对象,才能够被注入值,即必须被声明为@Component注解)

@Component
@ConfigurationProperties(prefix = "student")
public class Student {
    public static String name;
    public static int age;

    public void setName(String name){
        this.name = name;
    }

    public void setAge(int age){
        this.age = age;
    }
}


student:
  name: '小明'
  age: 15

3.可以使用@Configuration、@PropertySource(value=”classpath:test.properties”)、@ConfigurationProperties(prefix=”student”)这三个注解将resources文件下test.properties描述的student对象的属性注入到student对象中(即使用自定义的配置文件,将属性注入到对象中)。  @Configuration注解可以替换为@Component注解,@Configuration注解其实继承了@Component注解,用来表示该类是配置类。

@Configuration
@PropertySource(value="classpath:application.properties")
@ConfigurationProperties(prefix="student")
public class Student {
    public static String name;
    public static int age;

    public void setName(String name){
        Student.name = name;
    }

    public void setAge(int age){
        Student.age = age;
    }
}

test.properties的内容如下图

student.name = '小白'
student.age = 16



版权声明:本文为tanglihai原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。