实现步骤

  • 加入依赖
  • 创建类,在类中去加入注解
  • 创建spring的配置文件
    • 在文件中声明组件扫描器的标签,指名注解在你项目中的位置。
  • 使用注解创建对象,创建容器ApplicationContext

创建类

ba01.Student.java

  1. package com.chentianyu.ba01;
  2. import org.springframework.stereotype.Component;
  3. //得到Student这一类的对象得用@Component
  4. /**
  5. * @Component: 创建对象的,等同于<bean>的功能
  6. * 属性: value 就是对象的名称,也就是<bean id>;所以value的值是唯一的;创建对象在整个spring容器中就一个
  7. * 位置: 在类的上面
  8. * @Component(value = "myStudent")等同于<bean id="myStudent" class="com.chentianyu.ba01.Student" />
  9. */
  10. @Component(value = "myStudent")
  11. public class Student {
  12. private String name;
  13. private Integer age;
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public Integer getAge() {
  21. return age;
  22. }
  23. public void setAge(Integer age) {
  24. this.age = age;
  25. }
  26. @Override
  27. public String toString() {
  28. return "Student{" +
  29. "name='" + name + '\'' +
  30. ", age=" + age +
  31. '}';
  32. }
  33. }

得需要配置文件resources

创建spring的配置文件

resources > applicationContext.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. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. https://www.springframework.org/schema/context/spring-context.xsd">
  9. <!--声明组件扫描器(component-scan),组件就是java对象
  10. base-package: 指定你的注解在你的项目中的包名
  11. component-scan工作方式: Spring会扫描遍历base-package指定的包,把包中和子包中所有类,找到类中的注解,按照注解的功能创建对象或给属性赋值。
  12. 加入了component-scan标签, 配置文件的变化:
  13. 1.加入一个新的约束文件: spring-context.xsd
  14. 2.给这个新的约束文件起一个命名空间的名称(xmlns:context="http://www.springframework.org/schema/context")
  15. -->
  16. <context:component-scan base-package="com.chentianyu.ba01" />
  17. </beans>

创建容器ApplicationContext

第一个测试类MyTest01

package com.chentianyu;

import com.chentianyu.ba01.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest01 {
    @Test
    public void test01(){
        String config = "applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
        //从容器中获取对象(需要id(value里的就是id))
        Student student = (Student) applicationContext.getBean("myStudent");
        System.out.println(student);
    }
}
Student{name='null', age=null}

对象就有了