2022 Spring梳理 1 @Configuration的出现

Spring容器中添加组件:

1.@Bean标注在方法上,方法运行结束后,返回的对象会被注册到ioc容器中

2.@Import 导入外部的jar,或者批量导入逻辑组件

 

Bean实例类,Person类

public class Person {
    private String name;

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

    public String getName() {
        return name;
    }
}

 

传统的Spring项目,ioc容器中组件的注册需要xml文件进行配置,如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="com.tomasfeng.spring.bean.Person" id="person">
        <property name="name" value="TomasFeng"/>
    </bean>
</beans>

  主测试类运行时要导入xml配置

public class AnnotationMainTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
    }
}

 

在SpringBoot中,@Configuration代替了xml配置类,可以书写以下的配置类代替xml配置文件

@Configuration//这是一个代替xml的配置类
public class MainConfig {


    @Bean //标在方法上,返回的对象会被添加到容器。
    public Person person(){
        Person person = new Person();
        person.setName("TomasByConfiguration");
        return person;
    }
}

有了这就不在编写xml配置文件,组件的编写可以放在配置类中进行。

 

@Configuration//这是一个代替xml的配置类
posted @ 2022-01-20 11:48  Timeouting  阅读(62)  评论(0)    收藏  举报