本教程会讲解两种注册方式

  1. 通过xml配置文件的方式进行注册
  2. 通过@Bean注解的方式进行注册

创建Person类

该类用于讲解测试,之后的介绍中将注册该类的bean
代码如下:

  1. package com.tonyliu.bean;
  2. public class Person {
  3. private String name;
  4. private String age;
  5. public Person() {
  6. }
  7. public Person(String name, String age) {
  8. this.name = name;
  9. this.age = age;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getAge() {
  18. return age;
  19. }
  20. public void setAge(String age) {
  21. this.age = age;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Person{" +
  26. "name='" + name + '\'' +
  27. ", age='" + age + '\'' +
  28. '}';
  29. }
  30. }

通过xml配置文件的方式进行注册

创建xml配置文件

src\main\resources\beans.xml 创建 beans.xml 配置文件
文件内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="person" class="com.tonyliu.bean.Person">
  6. <property name="age" value="18"></property>
  7. <property name="name" value="tony"></property>
  8. </bean>
  9. </beans>

xml配置文件讲解

  • 该配置文件注入了一个id为person的bean(id=”person”)
  • 该bean对应的类型为Person类(class=”com.tonyliu.bean.Person”)
  • 在bean中使用<property>对类的两个属性进行了初始化

获取bean对象

  1. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
  2. // 根据id获取bean
  3. Person person = applicationContext.getBean("person",Person.class);
  4. 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 {

  1. @Bean
  2. public Person person(){
  3. return new Person("lisi","21");
  4. }

}

  1. <a name="JGDSC"></a>
  2. ## 获取bean对象
  3. ```java
  4. ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
  5. Person person = applicationContext.getBean(Person.class);
  6. System.out.println(person);
  7. String[] namesForType = applicationContext.getBeanNamesForType(Person.class);
  8. for (String name : namesForType) {
  9. System.out.println(name);
  10. }

bean的命名

默认情况下,bean的名称和方法名相同
如果想指定bean名称,可以通过注解来指点
例如@Bean("myPerson")