Bean的注册方式

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 + "]";
	}
	
}

 

测试代码:

package constxiong;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 测试 Bean 注册
 * @author ConstXiong
 */
@Configuration
@Import(Other.class)
public class Test {
	
	public static void main(String[] args) {
		// xml <bean> 注册
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring-bean-register.xml");
		User user1 = context.getBean("user1", User.class);
		System.out.println(user1);

		// @Bean 注册
		User user2 = context.getBean("user2", User.class);
		System.out.println(user2);

		// @Component 注册
		Friend friend = context.getBean("test.Friend", Friend.class);
		System.out.println(friend);

		// @Import 注册
		Other other = context.getBean("constxiong.Other", Other.class);
		System.out.println(other);

		// BeanDefinitionRegistry#registerBeanDefinition() 注册
		RootBeanDefinition beanDefinition = new RootBeanDefinition();
		beanDefinition.setBeanClass(User.class);
		MutablePropertyValues propertyValues = new MutablePropertyValues();
		propertyValues.addPropertyValue("id", 3);
		propertyValues.addPropertyValue("name", "custom");
		beanDefinition.setPropertyValues(propertyValues);
		((DefaultListableBeanFactory)context.getBeanFactory()).registerBeanDefinition("custom", beanDefinition);
		User custom = context.getBean("custom", User.class);
		System.out.println(custom);

		// BeanDefinitionReaderUtils#registerWithGeneratedName() 注册
		beanDefinition = new RootBeanDefinition();
		beanDefinition.setBeanClass(User.class);
		propertyValues = new MutablePropertyValues();
		propertyValues.addPropertyValue("id", 4);
		propertyValues.addPropertyValue("name", "util");
		beanDefinition.setPropertyValues(propertyValues);
		beanDefinition.setPrimary(true);
		BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, (DefaultListableBeanFactory)context.getBeanFactory());
		System.out.println(context.getBean(User.class));

		// AnnotatedBeanDefinitionReader#registerBean() 注册
		AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader((DefaultListableBeanFactory)context.getBeanFactory());
		reader.registerBean(User.class, "annotated");
		System.out.println(context.getBean("annotated", User.class));

		// SingletonBeanRegistry#registerBean() 注册
		context.getBeanFactory().registerSingleton("singleton", new User(6, "singleton"));
		System.out.println(context.getBean("singleton"));
	}

	@Bean
	static User user2() {
		return new User(1, "constxiong");
	}

	@Component
	static class Friend {
		private int id = 10;
		private String name = "friend";
		@Override
		public String toString() {
			return "Friend{" +
					"id=" + id +
					", name='" + name + ''' +
					'}';
		}
	}

}

class Other {
	private int id = 10;
	private String name = "other";
	@Override
	public String toString() {
		return "Other{" +
				"id=" + id +
				", name='" + name + ''' +
				'}';
	}
}

 

完整代码:006-spring-bean-register

 


【Java学习资源】整理推荐

 

 


【Java面试题与答案】整理推荐

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值