组件注册-@Configuration&Bean给容器中注册组件(1)

  ideal

从Spring3.0开始,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的``,作用为:配置spring容器(应用上下文)。

作为案例来解释

首先创建maven 项目 然后

pom.xml
导入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>

src/main/java路径下 package
新建包名 com.test.bean

创建实体类 Person.java

com/test/bean
创建类:Person.java

package com.test.bean;

/**
 * Created by shrstart on 2018/6/26.
 */
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(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }
}

创建配置类MainConfig.java

com/test/config包名下
创建MainConfig.java

package com.test.config;

import com.test.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置类==配置文件
 *
 *
 * Created by shrstart on 2018/6/26.
 */
@Configuration  //告诉Spring这是一个配置类
public class MainConfig {

    //给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
    @Bean("person")
    public Person person01(){
        return new Person("list",20);
    }

}

测试类MainTest.java

com/test
创建MainTest.java

package com.test;

import com.test.bean.Person;
import com.test.config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by shrstart on 2018/6/26.
 */
public class MainTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        Person bean = applicationContext.getBean(Person.class);
        System.out.println(bean);//输出 配置类MainConfi类下的 注解@ @Bean("person")

        String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
        for (String name : namesForType){
            System.out.println(name);//输出实体类名称
        }
    }
}

运行结果

Person{name='list', age=20}
person

本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处