注解开发定义bean
1、使用@Component注解定义bean
@Service("BookService")
public class BookServiceImpl implements BookService {
@Override
public void bookService() {
System.out.println("bookService");
}
}
2、核心配置文件中通过扫描加载bean
<?xml version="1.0" encoding="UTF-8"?>
<!--开启context命名空间-->
<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
http://www.springframework.org/schema/context/spring-context.xsd">
<!--使用注解定义bean 使用context:component-scan对包进行扫描-->
<context:component-scan base-package="com.itheima"/>
</beans>
Spring提供@Component注解的三个衍生注解
- @Controller:用于表现层bean定义
- @Service:用于业务层bean定义
- @Repository:用于数据层bean定义
纯注解开发模式
Spring3.0开启了纯注解开发模式,使用Java类代替配置文件,开启了Spring快速开发赛道 1、java类代替Spring核心配置文件 * 定义配置类 使用@Configuration定义当前类为配置类 使用ComponentScan注解设定扫描路径,此注解只能添加一次,多个数据请用数组格式定义扫描路径
// 配置类
@Configuration
@ComponentScan("com.itheima")
public class SpringConfig {
}
2、读取Spring核心配置文件初始化容器对象切换为读取Java配置类初始化容器对象