@Configuration & @Bean注册组件到容器

@Configuration & @Bean注册组件到容器

最开始的时候我们注册bean到容器中是通过Spring的xml配置文件来注册的, 很麻烦, 这里我们通过@Configuration和@Bean注解配合来注册组件到容器中
@Configuration注解是一个合成注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    ...
}
  • 可以看到@Configuration注解是@Component注解合成的, 而@Component注解是包扫描(ComponentScan)的对象, 所以说@Configuration注解也是包扫描的对象

1. 创建一个Person实体类(就是我们想要放到容器中的类)

package com.ffyc.spring.model;

public class Person {
    int id;
    String name;

    public Person() {

    }

    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

2. 创建一个配置类, 并创建一个注册Person对象到容器中的方法

  • 这一步其实就是使用@Configuration注解和@Bean注解
package com.ffyc.spring.config;

import com.ffyc.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PersonConfig {

    @Bean
    public Person getPerson() {
        return new Person();
    }
}

3. 创建一个测试类进行测试

package com.ffyc.spring.test;

import com.ffyc.spring.config.PersonConfig;
import com.ffyc.spring.model.Person;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test1 {
    public static void main(String[] args) {
//        ClassPathXmlApplicationContext
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
        Person bean = annotationConfigApplicationContext.getBean(Person.class);
        System.out.println(bean);
    }
}

加载配置类的方式获取Spring容器, 所以是通过AnnotationConfigApplicationContext类

通过加载xml配置文件方式获取Spring容器, 是通过ClassPathXmlApplicationContext类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值