Spring基于注解的IOC入门
模拟表现层,业务层,持久层的类
基于注解的IOC配置
Maven工程 pom.xml导入spring依赖
<?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>com.itheima</groupId>
<artifactId>spring_eesy_FirstIOC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.17.RELEASE</version>
</dependency>
</dependencies>
</project>
配置bean…xml文件
-
创建一个类路径下的xml
-
去Spring Framework Documentation官网CTRL+f 查找xmlns:context
3 -
将右侧红色框的内容复制到bean.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:comtext="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在bean的约束中,
而是一个名称为context名称空间和约束-->
<comtext:component-scan base-package="com.itheima"></comtext:component-scan>
</beans>
在com.itheima包下的任意类 使用注解@Component
public class Client {
/*
* 获取Spring的IOC核心容器,并根据id来获取对象*/
public static void main(String[] args){
//1.获取核心容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
IAccountService as = (IAccountService) applicationContext.getBean("accountServiceImpl");
//IAccountDao adao= applicationContext.getBean("accountDao",IAccountDao.class);
System.out.println(as);
}
}
@Component
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public AccountServiceImpl(){
System.out.println("对象创建了");
}
public void saveAccount(){
accountDao.saveAccount();
}
}