本教程会讲解两种注册方式
- 通过xml配置文件的方式进行注册
- 通过@Bean注解的方式进行注册
创建Person类
该类用于讲解测试,之后的介绍中将注册该类的bean
代码如下:
package com.tonyliu.bean;public class Person {private String name;private String age;public Person() {}public Person(String name, String age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age='" + age + '\'' +'}';}}
通过xml配置文件的方式进行注册
创建xml配置文件
在 src\main\resources\beans.xml 创建 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.tonyliu.bean.Person"><property name="age" value="18"></property><property name="name" value="tony"></property></bean></beans>
xml配置文件讲解
- 该配置文件注入了一个id为person的bean(id=”person”)
- 该bean对应的类型为Person类(class=”com.tonyliu.bean.Person”)
- 在bean中使用
<property>对类的两个属性进行了初始化
获取bean对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");// 根据id获取beanPerson person = applicationContext.getBean("person",Person.class);System.out.println(person);
通过注解方式进行注册
这里会涉及到两个注解,分别为:
- @Configuration:添加到类上,表明该类为配置类,相当于前面说到的xml文件
- @Bean:添加到方法上,将该方法作为bean注入
创建配置类文件
创建一个配置类:src\main\java\com\tonyliu\config\MainConfig.java
代码如下: ```java package com.tonyliu.config;
import com.tonyliu.bean.Person; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class MainConfig {
@Beanpublic Person person(){return new Person("lisi","21");}
}
<a name="JGDSC"></a>## 获取bean对象```javaApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);Person person = applicationContext.getBean(Person.class);System.out.println(person);String[] namesForType = applicationContext.getBeanNamesForType(Person.class);for (String name : namesForType) {System.out.println(name);}
bean的命名
默认情况下,bean的名称和方法名相同
如果想指定bean名称,可以通过注解来指点
例如@Bean("myPerson")
