spring注解开发的组件注册

在spring的底层中,重要特性是IoC和DI,即是控制反转依赖注入

spring认为所有组件都应该放在IoC容器中,然后组件之中的关系通过容器自动装配,也就是我们所说的依赖注入。

这篇文章主要介绍容器的组件注册管理。

 

以前通常是用配置文件来注册组件。例如

在bean配置文件使用bean标签。

beans.xml

	<bean id="person" class="com.xxx.bean.Person" >
		<property name="age" value="18"></property>//属性赋值
		<property name="name" value="zhangsan"></property>
	</bean>

测试类

MainTest.java

public class MainTest {
	
	public static void main(String[] args) {
//类路径下的xml配置文件,然后返回IoC容器		
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		Person bean = (Person) applicationContext.getBean("person");
		System.out.println(bean);
	}

}

这是过去我们常用的注册组件方式。

如果采用注解式开发,就需要把配置文件转换成配置类,其实配置类是等同于配置文件的,只是一个是java代码的方式,一个是xml配置的方式。

MainConfig.java

//配置类==配置文件
@Configuration  //告诉Spring这是一个配置类

public class MainConfig {
	
	//给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
        //@Bean跟Bean标签是一模一样的
	@Bean("person")//指定名字叫person,不允许通过方法名修改名字,这样在容器中就是person组件,而不是person01
	public Person person01(){
		return new Person("lisi", 20);//返回一个person对象
	}

}

相应的测试类也要修改为

MainTest.java

public class MainTest {
	
	@SuppressWarnings("resource")
	public static void main(String[] args) {
//		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//		Person bean = (Person) applicationContext.getBean("person");
//		System.out.println(bean);
		
                //以前传配置文件,现在传配置类
 		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
		Person bean = applicationContext.getBean(Person.class);
		System.out.println(bean);
		
		String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
		for (String name : namesForType) {
			System.out.println(name);
		}
	
	}

}

使用注解开发的方式,采用@Bean的注解将组件注册到容器中。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值