- 新建一个maven项目如图所示。
- 在pom文件中加入spring-context依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
- 创建一个Bean对象Person
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
- 创建配置类,注册Bean。
@Configuration //告诉Spring这是一个配置类
public class MainConfig {
//给容器注册一个Bean;类型为返回值的类型。id默认是用方法名作为id
@Bean
public Person person(){
return new Person("Lisa",18);
}
}
在Spring项目中,我们需要通过spring配置文件来注册Bean,现在交给注解完成。创建配置类,在配置类中完成Bean组件的注册。在这里,配置类===配置文件。
创建一个MainConfig.java类,然后在类名前加上@Configuration注解,该注解的目的是告诉Spring这是一个配置类。
然后在配置类中给容器注册一个Bean.使用@Bean标签来注册,方法的返回值为Bean的类型(对应Spring配置文件中注册Bean中的class。)id默认是用方法名作为id。当然,也可以不用方法名作为id,这是只需使用@Bean(“id值”)来设置id值。如下所示,可以将方法名换做任意的(比如person1),然后在@Bean中设置id值(比如person)。
@Bean("person")
public Person person1(){
return new Person("Lisa",18);
}
上面的方法在不使用注解开发时,和在spring配置文件中配置是一样的效果。
<bean id="person" class="com.fzl.bean.Person">
<property name="name" value="Lisa"></property>
<property name="age" value="18"></property>
</bean>
5.写一个测试类来测试。
此处通过Spring的方式,使用ApplicationContext 来加载配置类。
public class MainTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = applicationContext.getBean("person",Person.class);
System.out.println(person);
}
}
运行结果: