您的位置:首页 > 编程语言 > Java开发

超简单的Spring入门案例制作,快来看看吧!

2020-07-16 10:21 197 查看

Spring入门案例制作

1.构建方法:接口,实现类,测试方法

接口:
package com.itheima.service;

public interface UserService {
public void save();
}
实现类:
package com.itheima.service.imple;

import com.itheima.service.UserService;

public class UserServiceImpl implements UserService {
public void save() {
System.out.println("hello");
}
}
测试方法:
import com.itheima.service.UserService;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserApp {
public static <applicationConmtext> void main(String[] args) {
//加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取资源
UserService userService = (UserService) ctx.getBean("UserService");
userService.save();
}
}
创建路径:

2.导入坐标:spring-context

<dependencies>
<dependency>

<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>

</dependency>
</dependencies>

3.创建配置文件 applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<!--创建Spring控制的资源-->
<bean id="duj" class="com.itheima.service.imple.UserServiceImpl"/>

</beans>

4.加载配置文件:

ApplicationContext ctx = new ClassPathXmlApplicationContext(“配置文件名”)

获取资源: ctx.getBean(“里边填写的是配置文件里边的id名字,这个名字可以自己随便取,但一般都写接口名”)

ntext(“配置文件名”)

获取资源: ctx.getBean(“里边填写的是配置文件里边的id名字,这个名字可以自己随便取,但一般都写接口名”)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: