Spring5:Java Config

@Configuration

@Bean

@ComponentScan

@ImportResource

使用Java的方式配置spring,完全不使用spring配置文件,交给java来做!
两个注解非常重要:

@Configuration:相当于创建了spring配置文件的beans标签
@Bean:实例化对象 相当于创建了spring配置文件bean标签

定义一个Person 对象

package com.spring.Vo2;

import org.springframework.beans.factory.annotation.Value;

public class Person {

    @Value("king")
    private String name;

    public String getName() {
        return name;
    }
}

创建一个配置类MyConfig :bean的id就是方法名称

package com.spring.confing;

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

@Configuration
public class MyConfig {

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

测试:
通过AnnotationConfigApplicationContext对象获取Spring容器

 @Test
 public void test03(){
     //获取容器 AnnotationConfigApplicationContext
     ApplicationContext applicationContext =
             new AnnotationConfigApplicationContext(MyConfig.class);
     //获取bean
     Person person =applicationContext.getBean("person", Person.class);
     System.out.println(person.getName());
 }

扩展功能:扫描、合并注解

@Configuration
@ComponentScan(value = "com.spring.confing")
@ImportResource(value =MyConfig2.class )
posted @ 2020-04-01 16:18  努力的校长  阅读(198)  评论(0编辑  收藏  举报