1-组件注册-@configuration@Bean给容器中注册组件

本文知识点来源于尚硅谷,感谢尚硅谷为广大学子提供的优质教育资源,感谢各位老师热情指导,本文仅作为学习笔记使用,记录学习心得,如有不适,请联系作者。
新建maven工程

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.2.5.RELEASE</version>
</dependency>

被注入对象

public class Person {
	private String name;
	private Integer age;
	private String sex;

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Person(String name, Integer age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public String getName() {
		return name;
	}

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

	public Integer getAge() {
		return age;
	}

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

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

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

}

以前通过xml方式配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:p="http://www.springframework.org/schema/p"
       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.tedu.bean.Person">
		<property name="age" value= "18"></property>
		<property name="name" value= "张三"></property>
		<property name="sex" value= "男"></property>
	</bean>	
</beans>

测试类

public class MainTest_ConfigurationAndBean {
	public static void main(String[] args) {
		//以前通过xml配置的做法
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
		Person person = (Person) applicationContext.getBean("person");
		System.out.println(person);	
	}
}

输出:

Person [name=张三, age=18, sex=]

使用@Configuration和@Bean注解注册

/**
 * 配置类==配置文件xml
 * @author Administrator
 *
 */
@Configuration //告诉Spring这是一个配置类
public class MainConfig {
	
	/**
	 * 给容器注册一个bean,类型为返回值类型,id默认是方法名
	 * 如果想指定id 可以写作@Bean("person2") 
	 * 
	 * @return
	 */
	
	//@Bean这样写的话bean id默认为方法名
	@Bean("person2")//指定方法名
	public Person person() {
		return new Person("李四",18,"男");
	}
}
public class MainTest_ConfigurationAndBean {
	
	public static void main(String[] args) {
		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
		Person person = (Person) applicationContext.getBean(Person.class);
		System.out.println(person);
		String[] beanNames = applicationContext.getBeanNamesForType(Person.class);
		for (String beanName : beanNames) {
			System.out.println("beanName:" + beanName);
		}
	}
}

输出

Person [name=李四, age=18, sex=]
beanName:person2
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值