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);