spring的第一个例子,使用spring创建对象

spring的ioc,由spring创建对象

实现步骤:
1. 创建maven项目
2. 加入maven的依赖
spring的依赖 版本5.2.5
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
junit依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>

3. 创建类(接口和他的实现类)
和没有使用框架一样,就是普通的类
接口=====================================
1 package com.bjpowernode.service;
2 
3 public interface SomeService {
4     void doSome();
5 }
View Code

 

类=======================================
 1 package com.bjpowernode.service.impl;
 2 
 3 import com.bjpowernode.service.SomeService;
 4 
 5 public class SomeServiceImpl implements SomeService {
 6     public SomeServiceImpl() {
 7     }
 8 
 9     public void doSome() {
10         System.out.println("执行了SomeService的doSome方法");
11     }
12 }
View Code

 


4. 创建spring需要使用的配置文件
声明类的信息,这些类由spring创建和管理
 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
 5        http://www.springframework.org/schema/beans/spring-beans.xsd">
 6     <!--告诉spring创建对象-->
 7     <!--声明bean,告诉spring要创建某个类的对象
 8     id:对象的自定义名称,唯一值,spring通过这个名称找到对象
 9     class:类的全限定名称(不能是接口,因为spring使用的是反射的方法来创建对象,必须实用类)
10     以下bean标签就实现了SomeService someService = new SomeServiceImpl();的操作
11     spring把创建好的对象放到map中,spring框架中有个map存放对象的
12     springMap.put(id的值,对象);
13     springMap.put("someService",new SomeServiceImpl())
14 
15     一个bean声明一个java对象。
16     -->
17     <bean id="someService" class="com.bjpowernode.service.impl.SomeServiceImpl" />
18 
19 </beans>
20 <!--
21 spring 的配置文件
22 1. beans:是跟标签,spring把java对象成为bean
23 2. spring-beans.xsd是约束文件,和mybatis指定dtd是一样的,但是xsd更强
24 
25 -->
View Code

 


5. 测试spring创建的对象

 1     /*反转方式*/
 2     @Test
 3     public void test02(){
 4         //使用spring容器创建的对象
 5         //1. 指定spring配置文件的名称
 6         String config = "beans.xml";
 7         //2. 创建标识spring容器的对象,ApplicationContext
 8         //ApplicationContext就是标识Spring容器,可以通过容器获取对象了
 9         //ClassPathXmlApplicationContext:表示从类路径中加载spring的配置文件
10         ApplicationContext ac = new ClassPathXmlApplicationContext(config);
11         //从容器中获取对象,调用对象的方法,这个对象我们是没有new过的,由容器spring在beans.xml文件中帮我们去new了这个对象
12         SomeService service = (SomeService) ac.getBean("someService");
13         //使用spring创建好的对象调用方法
14         service.doSome();
15     }
View Code

 

posted @ 2021-02-26 00:29  渐行、渐远  阅读(129)  评论(0)    收藏  举报