01.Spring注解驱动开发——组件注册-@Configuration&@Bean给容器中注册组件

  1. 新建一个maven项目如图所示。
    在这里插入图片描述
  2. 在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>
  1. 创建一个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;
    }
}

  1. 创建配置类,注册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);
    }
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值