ssm整合之编写Spring框架

ssm整合之编写Spring框架

1.在resources目录下创建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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
    <context:component-scan base-package="com.txw">
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
</beans>

2.修改账户实现类的代码如下:

package com.txw.service.impl;

import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * 账户业务的实现类
 * @author Adair
 */
@Service("accountService")
@SuppressWarnings("all")     // 注解警告信息
public class AccountServiceImpl implements AccountService {
    
    
    /**
     * 查询所有账户
     * @return
     */
    @Override
    public List<Account> findAll() {
    
    
        System.out.println("业务层:查询所有账户...");
        return null;
    }
    /**
     * 保存帐户信息
     * @param account
     */
    @Override
    public void saveAccount(Account account) {
    
    
        System.out.println("业务层:保存帐户信息...");
    }
}

声明@Service(“accountService”)是把业务层实现类叫交给IOC容器进行管理。
3.编写一个测试类的代码如下:

package com.txw.test;

import com.txw.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * 测试类
 * @author Adair
 */
@SuppressWarnings("all")     // 注解警告信息
public class TestSpring {
    
    
    @Test
    public void run1(){
    
    
        // 加载配置文件
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        // 获取对象
        AccountService as = (AccountService) ac.getBean("accountService");
        // 调用方法
        as.findAll();
    }
}

运行结果如图所示:在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40055163/article/details/109219708
今日推荐