2 Spring IoC

目录

POM

案例一,基于 xml 配置

创建 entity

创建 Spring 配置文件

测试 Spring IoC

案例一,基于注解配置

改造 entity

改造 Spring 配置文件

改造测试类 Spring IoC

案例二,基于 xml 配置

创建 StudentService 接口

创建 UserServiceImpl 实现类

创建 Spring 配置文件

测试 Spring IoC

案例二,基于注解配置

改造实现类,加上注解 @Service

改造 Spring 配置文件

改造测试类 Spring IoC


POM

创建一个工程名为 spring-ioc-demo 的项目,pom.xml 文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>spring-ioc-demo</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>

        <spring.version>5.1.5.RELEASE</spring.version>
        <lombok.version>1.16.20</lombok.version>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <slf4j.version>1.7.25</slf4j.version>
    </properties>

    <dependencies>

        <!-- Spring Begin -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring End -->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <!-- lombok Begin -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- lombok End -->

        <!-- Log Begin -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <!-- Log End -->

    </dependencies>

    <build>
        <plugins>
            <!-- Compiler 插件, 设定 JDK 版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

核心包:主要增加了 org.springframework: spring-context 依赖

案例一,基于 xml 配置

创建 entity

@Data
public class Student {
    private int id;
    private String name;
    private String email;
    private String address;
    private Hobboy hobboy;
}
@Data
public class Hobboy {
    private String basketball;
    private String football;
    private String running;
}

创建 Spring 配置文件

在 src/main/resources 目录下创建 spring-context.xml 配置文件,从现在开始类的实例化工作交给 Spring 容器管理(IoC),配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <bean id="stu" class="com.example.spring.demo.entity.Student">
        <property name="id" value="10"></property>
        <property name="name" value="vincent"></property>
        <property name="email" value="601521821@qq.com"></property>
        <property name="address" value="上海市、宝山区"></property>
        <property name="hobboy" ref="hob"></property>
    </bean>
    <bean id="hob" class="com.example.spring.demo.entity.Hobboy">
        <property name="basketball" value="Nike"></property>
        <property name="football" value="Adidas"></property>
        <property name="running" value="5km"></property>
    </bean>

</beans>

<bean/>:用于定义一个实例对象。一个实例对应一个 bean 元素。

id:该属性是 Bean 实例的唯一标识,程序通过 id 属性访问 Bean,Bean 与 Bean 间的依赖关系也是通过 id 属性关联的。

class:指定该 Bean 所属的类,注意这里只能是类,不能是接口

测试 Spring IoC

创建一个 GetBeanTest 测试类,测试对象是否能够通过 Spring 来创建,代码如下:

public class GetBeanTest {

    @Test
    public void testGetBean() {
    	ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        Student stu = (Student) applicationContext.getBean("stu");
        System.out.println(stu);
    }
}

测试结果:

Student(id=10, name=vincent, email=601521821@qq.com, address=上海市、宝山区, hobboy=Hobboy(basketball=Nike, football=Adidas, running=5km))

案例一,基于注解配置

改造 entity

@Data
@Component
public class Student {
    @Value("10")
    private int id;

    @Value("Vincrnt")
    private String name;

    @Value("601521821@qq.com")
    private String email;

    @Value("上海市宝山区")
    private String address;

    @Autowired
    private Hobboy hobboy;
}

@Data
@Component
public class Hobboy {
    @Value("Nike")
    private String basketball;

    @Value("Adidas")
    private String football;

    @Value("5km")
    private String running;
}

改造 Spring 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <!-- 开启自动注解 -->
    <context:annotation-config/>
    
    <!-- 扫描全部的整个项目的包 -->
    <context:component-scan base-package="com.example.spring.ioc.demo"/>

</beans>

改造测试类 Spring IoC

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-context.xml")
public class GetBeanTest {

    @Autowired
    private Student student;

    @Test
    public void annotationStu(){
        System.out.println(student);
    }

}

测试结果:

Student(id=10, name=vincent, email=601521821@qq.com, address=上海市、宝山区, hobboy=Hobboy(basketball=Nike, football=Adidas, running=5km))

案例二,基于 xml 配置

创建 StudentService 接口

public interface StudentService {
    public void sayHi();
}

创建 UserServiceImpl 实现类

public class StudentServiceImpl implements StudentService {
    public void sayHi() {
        System.out.println("Hello Spring IoC !!!");
    }
}

创建 Spring 配置文件

在 src/main/resources 目录下创建 spring-context.xml 配置文件,从现在开始类的实例化工作交给 Spring 容器管理(IoC),配置文件如下:

<?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="studentService" class="com.example.spring.demo.service.impl.StudentServiceImpl" />
</beans>

<bean />:用于定义一个实例对象。一个实例对应一个 bean 元素。

id:该属性是 Bean 实例的唯一标识,程序通过 id 属性访问 Bean,Bean 与 Bean 间的依赖关系也是通过 id 属性关联的。

class:指定该 Bean 所属的类,注意这里只能是类,不能是接口。

测试 Spring IoC

创建一个 GetBeanTest 测试类,测试对象是否能够通过 Spring 来创建,代码如下:

public class GetBeanTest {
    @Test
    public void sayHi() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        StudentService studentServiceImpl = (StudentService) applicationContext.getBean("studentService");
        String sayHi = studentServiceImpl.sayHi();
        System.out.println(sayHi);
    }
}

测试结果

Hello Spring IoC !!!

案例二,基于注解配置

改造实现类,加上注解 @Service

@Service
public class StudentServiceImpl implements StudentService {
    @Override
    public String sayHi() {
        return "Hello Spring IoC !!!";
    }
}

改造 Spring 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <!-- 开启自动注解 -->
    <context:annotation-config/>
    
    <!-- 扫描全部的整个项目的包 -->
    <context:component-scan base-package="com.example.spring.ioc.demo"/>

</beans>

改造测试类 Spring IoC

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-context.xml")
public class GetBeanTest {
    @Autowired
    private StudentService studentService;

    @Test
    public void annotationSayHi() {
        String sayHi = studentService.sayHi();
        System.out.println(sayHi);
}

测试结果:

Hello Spring IoC !!!
  • 68
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 28
    评论
### 回答1: Spring IOC (Inversion of Control) 是 Spring 框架中的一个核心功能,它通过依赖注入 (Dependency Injection, DI) 的方式在运行时动态地将对象的依赖关系注入到对象中。这样做的好处是可以使得对象之间的依赖关系更加灵活,且对象的创建和使用变得更加简单。 具体来说,Spring IOC 容器会管理所有的对象,并在运行时根据配置的信息将这些对象的依赖关系注入到对象中。这些对象被称为 Spring Beans,Spring IOC 容器负责创建、配置和管理这些 Spring Beans。 使用 Spring IOC 可以使程序更加灵活,因为对象之间的依赖关系可以在运行时动态地注入,而不是在编译时确定。这样可以使得程序更加灵活,可以更好地应对变化。 总的来说,Spring IOC 是一种设计模式,用于管理对象之间的依赖关系,使得对象之间的耦合度降低,使程序变得更加灵活。 ### 回答2: Spring IOCSpring 框架的核心特性之一,全称为控制反转(Inversion of Control)。 IOC 是一种设计模式,它将程序的控制权从应用程序自身转移到了框架上,由框架来控制应用程序的对象创建和管理。传统的开发方式是通过代码来直接创建对象并管理依赖关系,而 IOC 则将这部分控制权交给了框架。 在 Spring 中,IOC 容器扮演着重要的角色,它负责初始化对象、管理对象之间的依赖关系,并在应用程序运行期间进行对象的生命周期管理。通过配置文件或注解的方式,开发者只需描述需要的对象以及对象之间的依赖关系,而无需手动去实例化和管理对象。 使用 Spring IOC 的好处主要有三个方面: 1. 开发效率提高:由于 IOC 容器负责对象的创建和管理,开发者只需要关注对象的逻辑实现,无需关心对象的创建和销毁,大大提高了开发效率。 2. 代码解耦:IOC 的设计思想强调松耦合,对象之间的依赖关系通过配置文件或注解来描述,减少了代码间的硬编码,便于维护和扩展。 3. 更好的测试性:由于对象的创建和管理交给了容器,开发者可以使用模拟对象进行单元测试,而不需要依赖真实的对象,提高了测试的灵活性。 总而言之,Spring IOC 是一种基于控制反转的设计模式,将对象的创建和管理交给了框架,提高了开发效率、代码解耦和测试的灵活性。 ### 回答3: SpringIOC(Inversion of Control)是一种编程思想,也是Spring框架的核心特性之一。通过IOC,控制权由程序员转移到了Spring容器中,由容器负责对象的创建和管理。 在传统的开发模式中,对象的创建和管理都需要由程序员手动完成,而使用Spring IOC可以将这一任务交给Spring容器完成。程序员只需通过配置文件或注解来告诉Spring容器需要创建哪些对象,而具体的对象创建、依赖注入等工作都由容器自动完成。 Spring IOC的优势主要有以下几点: 1. 松耦合:通过IOC,对象之间的依赖关系由容器来管理,提高了代码的灵活性和可维护性。 2. 可测试性:IOC可以通过依赖注入的方式来注入对象,方便进行单元测试。 3. 配置灵活:使用配置文件或注解可以灵活地配置对象的创建和依赖关系,可以方便地进行修改和扩展。 4. 容器管理:Spring容器可以管理对象的生命周期、作用域等,使得对象的创建和销毁更加方便和可控。 Spring IOC的实现方式有两种:XML配置和注解方式。在XML配置中,需要手动配置对象的创建和依赖关系;而在注解方式中,可以通过注解来自动配置对象的创建和依赖关系。 总而言之,Spring IOC是一种通过将对象的创建和管理交给容器来实现松耦合、可测试、配置灵活和容器管理的编程思想,大大提高了代码的可维护性和可扩展性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清风絮柳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值