Bean的注册方式

2021-01-25

Bean 的注册方式:

  • xml <bean>
  • @Bean 注解
  • @Component 及其派生出来的注解 @Service、@Controller、@Repository;其他规范类似功能的注解,@Resource、@Inject
  • @Import
  • BeanDefinitionRegistry#registerBeanDefinition
  • BeanDefinitionReaderUtils#registerWithGeneratedName
  • AnnotatedBeanDefinitionReader#register
  • SingletonBeanRegistry#registerSingleton

...

 

代码示例:

pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>constxiong</groupId>
        <artifactId>spring-study</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
	
    <artifactId>006-spring-bean-register</artifactId>

    <properties>
        <spring-version>5.2.2.RELEASE</spring-version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-version}</version>
        </dependency>
    </dependencies>

    <build>

    </build>
</project>

 

spring 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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="user1" class="constxiong.User"/>

    <!-- 开启注解能力 -->
    <context:component-scan base-package="constxiong"/>

</beans>

 

User 类

package constxiong;

public class User {
	
	private Integer id;
	
	private String name;
	
	public User() {
	}
	
	public User(Integer id, String name) {
		this.id = id;
		this.name = name;
	}

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}
	
}

 

测试代码:

ConstXiong 备案号:苏ICP备16009629号-3