首页 > 编程语言 > 详细

1.Spring框架入门案例

时间:2018-08-08 23:16:14      阅读:186      评论:0      收藏:0      [点我收藏+]

一、简单入门案例

入门案例:IoC

 

1.项目创建与结构

技术分享图片

 

2.接口与实现类

User.java接口
package com.jd.ioc;

/**
 * @author weihu
 * @date 2018/8/8/008 22:29
 * @desc 用户接口
 */
public interface User {
    void addUser();
}

UserImpl.java实现类
package com.jd.ioc.impl;

import com.jd.ioc.User;

/**
 * @author weihu
 * @date 2018/8/8/008 22:30
 * @desc 用户实现类
 */
public class UserImpl implements User {
    @Override
    public void addUser() {
        System.out.println("add user!");
    }
}

xml配置文件

beans.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">
    <!-- 配置service
        <bean> 配置需要创建的对象
            id :用于之后从spring容器获得实例时使用的
            class :需要创建实例的全限定类名
    -->
    <bean id="userServiceId" class="com.jd.ioc.impl.UserImpl"></bean>
</beans>

 

测试类

UserTest.java

package com.jd.test;

import com.jd.ioc.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author weihu
 * @date 2018/8/8/008 22:33
 * @desc ioc测试类
 */
public class UserTest {

    @Test
    public void testUser(){
        //1.加载配置文件
        String xmlPath= "com/jd/xml/beans.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        //根据id获取bean对象
        User user = (User) applicationContext.getBean("userServiceId");
        user.addUser();

    }
}

 

1.Spring框架入门案例

原文:https://www.cnblogs.com/weihu/p/9446318.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!