赞
赏
搭建 Spring 开发环境,使用基于注解配置的 Spring IOC 创建对象。
搭建 Spring 的开发环境,使用基于注解配置的 Spring IOC 创建对象。
pom 文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.haicoder</groupId>
<artifactId>SpringDemo08</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--IOC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
</dependencies>
</project>
核心配置文件:
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--自动扫描包-->
<context:component-scan base-package="net.haicoder"/>
</beans>
实体类:
@Component
public class User {
public User() {
System.out.println("创建实体类对象!");
}
}
持久层:
@Repository
public class UserDao {
public UserDao() {
System.out.println("创建持久层对象!");
}
}
业务层接口:
@Service
public class UserService {
public UserService() {
System.out.println("创建业务层对象!");
}
}
控制层
@Controller
public class UserController {
public UserController() {
System.out.println("创建控制层对象!");
}
}
测试类:
public class DemoTest {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
// IOC容器
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
// 创建实体类对象
User user = (User) act.getBean("user");
// 创建持久层对象
UserDao userDao = (UserDao) act.getBean("userDao");
// 创建业务层对象
UserService userService = (UserService) act.getBean("userService");
// 创建控制层对象
UserController userController = (UserController) act.getBean("userController");
}
}
运行结果如下:
以上案例使用基于注解配置的 Spring IOC 创建对象。