使用spring框架,通过spring容器来创建对象并使用

使用spring框架,通过spring容器来创建对象并使用

spring容器创建对象并使用的步骤如下:

第一,在pom.xml文件中配置spring框架

<!--    加入springframework依赖-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.3</version>
    </dependency>

第二步,配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--告诉spring创建对象
        声明bean , 就是告诉spring要创建某个类的对象
        id:对象的自定义名称,唯一值。 spring通过这个名称找到对象
        class:类的全限定名称(不能是接口,因为spring是反射机制创建对象,必须使用类)

        spring就完成 SomeService someService = new SomeServiceImpl();
        spring是把创建好的对象放入到map中, spring框架有一个map存放对象的。
           springMap.put(id的值, 对象);
           例如 springMap.put("someService", new SomeServiceImpl());

        一个bean标签声明一个对象。
    -->
    <bean id="studentOne" class="per.pcqstart.dao.impl.StudentDaoImpl"/>
    <bean id="student" class="per.pcqstart.domain.Student"></bean>

    <!--
       spring能创建一个非自定义类的对象吗, 创建一个存在的某个类的对象。
    -->
    <!--   <bean id="mydate" class="java.util.Date" /> -->

</beans>
        <!--
   spring的配置文件
   1.beans : 是根标签,spring把java对象成为bean。
   2.spring-beans.xsd 是约束文件,和mybatis指定  dtd是一样的。
-->

第三步,创建相应类和接口
①创建student.java,

public class Student {
    private Integer id;
    private String studentNumber;
    private String name;
    private String subject;
    private Integer score;
    }

②studentDao.interface

public interface StudentDao {
    public void sayHello();
}

③StudentDaoImpl.java

public class StudentDaoImpl implements StudentDao {
    @Override
    public void sayHello() {
        System.out.println("hello ,l am springBuildObject!!!");
    }
}

第四步,测试

//测试,使用spring容器创建StudentDaoImpl对象,并且使用该对象
@Test
public void test(){
    //1、读取spring配置文件,从classes根路径开始搜索
    String config = "spring.xml";
//    2.创建spring容器对象,就是ApplicationContext
//    在读取配置文件时,容器就通过无参构造方法创建了spring配置文件中所有的bean对象
//    在读取配置文件时,容器就通过无参构造方法创建了spring配置文件中所有的bean对象
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(config);
    StudentDao studentOne = (StudentDao) ac.getBean("studentOne");
    Student student = (Student) ac.getBean("studnent");
    System.out.println(student);
    studentOne.sayHello();
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值