Spring IOC新手入门

Spring IOC新手入门

        IOC(inversion of control)的中文解释是“控制反转”,对象的使用者不是创建者. 作用是将对象的创建 反转给spring框架来创建和管理。我们用到的对象都由Spring框架创建,使用对象时用对象的接口接受,能减少代码之间的耦合。

  • 创建Maven工程, 添加坐标

pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • 准备好接口和实现类

StudentService.java
package cn.appmy;

public interface StudentService {
    String getData();
}
StudentServiceImpl.java
package cn.appmy.impl;

import cn.appmy.StudentService;

public class StudentServiceImpl implements StudentService {
    @Override
    public String getData() {
        return "菜菜";
    }
}
  • 创建spring的配置文件 (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">

    <bean class="cn.appmy.impl.StudentServiceImpl" id="studentService"></bean>
</beans>
  • 创建工厂对象 获得bean 调用

import cn.appmy.StudentService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    @Test
    public void Stest(){
        ApplicationContext act=new ClassPathXmlApplicationContext("spring.xml");
        StudentService studentService =(StudentService) act.getBean("studentService");

        System.out.println(studentService.getData());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_慎

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

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

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

打赏作者

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

抵扣说明:

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

余额充值