ssm整合——Spring配置(2)

配置Spring

1. 环境准备

  • 使用之前搭建Mabatis的环境

1.1 新建目录

  • 新建spring的service业务逻辑包
  • 在resources目录下新建spring的配置文件:applicationContext.xml
  • 在test目录下新建spring的测试文件 在这里插入图片描述

1.2 文件配置

  • pom.xml
  • 在之前mybatis的基础上需要导入的jar包如下
<!-- spring所需的jar包-->
<dependency>
  <!-- spring创建上下文-->
  <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.0.RELEASE</version> </dependency> <dependency> <!-- spring结合junit进行测试--> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.0.RELEASE</version> </dependency> 复制代码
  • applicationContext.xml
  • 这里用注解注入service的bean对象
  • 上面的依赖链接随着内容的扩充而变化
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--表示开启注解扫描,配置了需要扫描的包--> <context:component-scan base-package="com.ow"></context:component-scan> </beans> 复制代码

2. 编写程序

2.1 IUserService接口

  • 这里先简单通过一个方法来测试
public interface IUserService {
    void saveUser(); } 复制代码

2.2 IUserServiceImpl.java

  • 这里编写接口的实现类,将实现类通过@Service进行注入,也可以通过@Service("XXX")为其指定名称
@Service
public class IUserServiceimpl implements IUserService { public void saveUser(){ System.out.println("业务层方法执行"); }; } 复制代码

2.2 测试程序

// 这里的注解表示通过配置文件生成容器的上下文,无需使用:new ClassPathXmlApplicationContext("bean.xml");
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest { //直接可以注入 @Autowired private IUserService service; @Test public void run1(){ service.saveUser(); } } 复制代码

欢迎关注我的公众号,了解一个学设计却做了运营最后成了数据分析师并努力成为大数据工程师的女程序员的成长之路。

在这里插入图片描述

作者:老巫婆
链接:https://juejin.im/post/5dfb8375e51d45584006e5d1
来源:掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/oldwitch/p/12070550.html
今日推荐