ssm整合-编写spring框架02

把类交给ioc进行管理

首先创建spring的配置文件

 

 开启注解扫描:

 

 

<?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="cn.itcast">
<!--配置那些注解不扫描,type是类型(为注解),expression是注解的全路径-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
</beans>


给service添加注解:
把service的类交给spring的ioc容器进行管理,id是accountService

 

 

创建test的包(测试用):

创建测试类TestSpring

 

 

package cn.itcast.test;

import cn.itcast.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {

@Test
public void run1() {
// 加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 获取对象
AccountService as = (AccountService) ac.getBean("accountService");
// 调用方法
as.findAll();
}
}

拷贝log4j配置文件到项目中去,测试时就不会出现红字:

 

 

 

posted @ 2020-06-01 20:33  Pykingchen  阅读(91)  评论(0编辑  收藏  举报