1,引入依赖(pom.xml)
2, 配置beans.xml文件
3, 建立项目测试
4, 关系图
1,在pom.xml依赖引入(引入新依赖时要刷新)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
<scope>test</scope>
</dependency>
2,配置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">
</beans>
3,建立测试项目
dao层(UserMapper)
package com.a2003.dao;
public interface UserMapper {
public void getUser();
public void deleteUser();
}
dao层(UserMapperImpl)
package com.a2003.dao;
public class UserMapperImpl implements UserMapper{
@Override
public void getUser() {
System.out.println("获取mysql用户信息!");
}
@Override
public void deleteUser() {
System.out.println("删除用户信息!");
}
}
dao层(UserMapperOraclImpl)
package com.a2003.dao;
public class UserMapperOraclImpl implements UserMapper{
@Override
public void getUser() {
System.out.println("Oracl获取用户信息");
}
@Override
public void deleteUser() {
}
}
service层(UserService)
用户
package com.a2003.service;
public interface UserService {
public void getUser();
}
service层(UserServiceImpl)
package com.a2003.service;
import com.a2003.dao.UserMapper;
import com.a2003.dao.UserMapperImpl;
public class UserServiceImpl implements UserService{
//private UserMapper userMapper = new UserMapperImpl();
private UserMapper userMapper;
public void setUserMapper(UserMapper userMapper){
this.userMapper = userMapper;
}
@Override
public void getUser() {
userMapper.getUser();
}
}
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">
<bean id="UserMapperImpl" class="com.a2003.dao.UserMapperImpl"></bean>
<bean id="UserMapperOraclImpl" class="com.a2003.dao.UserMapperOraclImpl"></bean>
<bean id="service" class="com.a2003.service.UserServiceImpl">
<property name="userMapper" ref="UserMapperOraclImpl"></property>
</bean>
</beans>
测试MyTest
import com.a2003.dao.UserMapperOraclImpl;
import com.a2003.service.UserService;
import com.a2003.service.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void getUserTest(){
UserService service = new UserServiceImpl();
((UserServiceImpl) service).setUserMapper(new UserMapperOraclImpl());
service.getUser();
service.getUser();
}
@Test
public void getUserTest2(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = applicationContext.getBean("service",UserService.class);
userService.getUser();
}
}
运行截图