通常我们使用 @value 来实现对装配对象的字段初始化默认值。value 传简单值,对应的注解写法就是:

private final String name;
public Student(@Value("10") String name){   //只不过,这里都是常量值了,我干嘛不直接写到代码里呢
    this.name = name;
}

除此之外,我们还可以访问外部的配置文件来进行初始化值,需要在配置类中添加 @PropertySource 注解:

@Configuration
@ComponentScan("com.test.bean")
@PropertySource("classpath:test.properties")   //注意,类路径下的文件名称需要在前面加上classpath:
public class MainConfiguration{
    
}

接着就可以将 @Value 放在其他位置上,例如初始化name:

@Component
public class Student {
    @Value("${test.name}")   //这里需要在外层套上 ${ }
    private String name;   //String会被自动赋值为配置文件中对应属性的值
 
    public void hello(){
        System.out.println("我的名字是:"+name);
    }
}

也可以添加在方法参数中:

@Component
public class Student {
    private final String name;
 
  	//构造方法中的参数除了被自动注入外,我们也可以选择使用@Value进行注入
    public Student(@Value("${test.name}") String name){
        this.name = name;
    }
 
    public void hello(){
        System.out.println("我的名字是:"+name);
    }
}