このブログのデモ元アドレス
https://github.com/suchahaerkang/spring-annotation.git
引数なしのコンストラクタでオブジェクトを作成するための1
まず、私たちはクラス構成を記述し、人へのコンテナに登録部品になります
/**
* @description:
* @author: sukang
* @date: 2020-03-07 11:00
*/
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
人アセンブリ
/**
* @description:
* @author: sukang
* @date: 2020-03-04 12:06
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Person {
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//姓名
private String name;
//年龄
private int age;
//昵称
private String nikeName;
}
書き込みテストケース
@Test
public void test01(){
//创建容器
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
//从容器中获取id为person的Person组件
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
業績
![ここの挿入の説明](https://img-blog.csdnimg.cn/20200307112252424.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3N1Y2hhaGFlcmthbmc=,size_16,color_FFFFFF,t_70
2コンポーネントプロパティの割り当て
アセンブリコンストラクタによって作成された場合を除いて@value注釈割り当て、それらは、参照割り当てを有するだけでなく、ばねによって提供されています
2.1 @value
@Value给属性赋值有三种方式
1) @Value("xxx"),直接加上想要赋的值
2) @Value("#{}") ,也可以通过spring提供的SPEL表达式来赋值
3) @Value("${}"),也可以通过注解@PrepertySource的方式将配置文件注入到运行环境中,然后通过${}的方式去获取
レッツ・テスト・モード1と2
/**
* @description:
* @author: sukang
* @date: 2020-03-04 12:06
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Person {
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//姓名
@Value("张三")
private String name;
//年龄
@Value("#{20-2}")
private int age;
//昵称
private String nikeName;
}
業績
その後、私たちは第三の方法をテスト
ファーストを、私たちは、あなたのクラスパスにperson.properties設定ファイルを追加
して、プロファイルに@PropertySourceコメントを追加
/**
* @description:
* @author: sukang
* @date: 2020-03-07 11:00
*/
@PropertySource(value={"classpath:/person.properties"},encoding = "utf-8")
@Configuration
public class MainConfigOfPropertyValues {
@Bean
public Person person(){
return new Person();
}
}
最後に、コンポーネント上の人でニックネームプロパティは、ノートをマーク
//昵称
@Value("${person.nickName}")
private String nickName;
業績
2.2 @PropertySource
この注釈は、実際に動作環境の値にキーと値の内部の指定された設定ファイルの中に注入された
ここでは、取得person.nickNameの値に環境変数をテスト
書き込みテストケース
@Test
public void test02(){
//创建容器
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
//从容器中获取环境变量组件
Environment environment = applicationContext.getEnvironment();
//从环境变量中获取person.nickName值
String nickName = environment.getProperty("person.nickName");
System.out.println("从环境变量中获取的nickName为:" + nickName);
}
業績