Spring组件注册 - springboot实战电商项目mall4j

本文详细介绍了Spring Boot中bean的注册方式,包括传统的XML注册、注解注册,以及排除与导入过滤器的使用。还讨论了作用域、懒加载、按条件注册、ImportSelector和ImportBeanDefinitionRegistrar的用法,最后提到了实现FactoryBean<?>接口和通过BeanDefinitionBuilder创建bean的方法。内容源自springboot实战电商项目mall4j。
摘要由CSDN通过智能技术生成

springboot实战电商项目mall4j (https://gitee.com/gz-yami/mall4j)

java商城系统源码

1. bean注册

我们有个Person类

public class Person {
   

	private Integer age;
	
	private String name;

	public Integer getAge() {
   
		return age;
	}

	public void setAge(Integer age) {
   
		this.age = age;
	}

	public String getName() {
   
		return name;
	}

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

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

1.1 传统bean注册

新建beans.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 id="person" class="com.opgame.spring.Person">
		<property name="age" value="18"/>
		<property name="name" value="张三"/>
	</bean>

</beans>

使用person对象进行测试

@Test
public void testBean() {
   
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
	Person person = (Person)context.getBean("person");
	System.out.println(person);
}

1.2 使用annotation代替xml注册

创建一个带有@Configuration的java类,使用 @Bean进行注册

@Configuration // 告诉spring这个是一个config类
public class BeansConfig {

	// 给容器注册一个bean,类型为返回值类型,默认id为方法名,在bean注解中设置id
	@Bean("person")
	public Person person() {
		Person person = new Person();
		person.setAge(20);
		person.setName("李四");
		return person;
	}
}

使用person对象进行测试

@Test
public void testBean
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值