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

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

 

 

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值