Spring组件注册之@Configuration

1.在以前使用Spring的时候,配置bean需要在xml中设置,基本步骤如下
1.1写一个实体类

package com.chd.dao;

public class Person {
	
	private String username;
	private Integer age;
	
	public String getusername() {
		return username;
	}
	public void setusername(String username) {
		this.username = username;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Person [username=" + username + ", age=" + age + "]";
	}
	public Person(String username, Integer age) {
		super();
		this.username = username;
		this.age = age;
	}
	public Person() {
		super();
	}
	
}

1.2在写一个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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
     <bean class="com.chd.dao.Person" id="person">
		<property name="username" value="chd"></property> 
		<property name="age" value="18"></property>    
     </bean>

</beans>

1.3测试类

package com.chd.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chd.dao.Person;

public class MainConfig {

		public static void main(String[] args) {
			 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
			 Person bean=(Person)applicationContext.getBean("person");
			 System.out.println(bean);
		}
}

1.4输出结果如下
在这里插入图片描述
2.使用注解配置
2.1写一个注解配置类

package com.chd.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,
//这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
@Configuration 
@ComponentScan(value = "chd") //扫描chd包下的类
public class MainConfig {
	
	@Bean//产生一个Bean,然后交给Spring容器
	public com.chd.dao.Person Person() {
		return new com.chd.dao.Person("xbh",18);
	}
		
}

2.2测试类测试

 ApplicationContext applicationContext= new AnnotationConfigApplicationContext(MainConfig.class);
		 Person person= applicationContext.getBean(Person.class);
		 System.out.println(person);

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微微笑再加油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值