项目结构
pom.xml
<dependencies>
<!-- <dependency>-->
<!-- <groupId>org.springframework</groupId>-->
<!-- <artifactId>spring-context</artifactId>-->
<!-- <version>5.2.0.RELEASE</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.spring</groupId>
<artifactId>spring-demo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="userMapper" class="com.spring.mapper.impl.UserMapperImpl">
<property name="name" value="孙笑川"/>
<property name="password" value="123456"/>
</bean>
<bean id="userService" class="com.spring.service.impl.UserServiceImpl">
<property name="userMapper" ref="userMapper"/>
</bean>
</beans>
mapper 数据访问层
UserMapper
public interface UserMapper {
/**
* 添加
*/
void add();
}
UserMapperImpl
public class UserMapperImpl implements UserMapper {
private String name;
private String password;
public UserMapperImpl() {
System.out.println("UserMapper被创建了");
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void add() {
System.out.println("UserMapper..." + "name: " + name + ",password: " + password);
}
}
service 业务逻辑层
UserService
public interface UserService {
/**
* 添加
*/
void add();
}
UserServiceImpl
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
public UserServiceImpl() {
System.out.println("UserService被创建了");
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public void add() {
System.out.println("UserService...");
userMapper.add();
}
}
Controller
public class UserController {
public static void main(String[] args) throws Exception {
//创建spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
//从容器中获取userService对象
UserService userService = (UserService) applicationContext.getBean("userService");
//业务逻辑处理
userService.add();
/*
UserMapper被创建了
UserService被创建了
UserService...
UserMapper...name: 孙笑川,password: 123456
*/
}
}
评论 (0)