目录
一、注解开发定义bean
二、纯注解开发
一、注解开发定义bean
使用@Component定义bean
@Component("bookDao")
public class BookDaoImpl implements BookDao {
}
@Component
public class BookServiceImpl implements BookService {
}
核心配置文件中通过组件扫描加载bean
Spring提供@Compoent注解的三个衍生注解
■ @Controller:用于表现层bean的定义
■ @Service:用于业务层bean定义
■ @Repository:用于数据层bean定义
@Repository("bookDao")
public class BookDaoImpl implements BookDao {
}
@Service
public class BookServiceImpl implements BookService {
}
二、纯注解开发
Spring3.0升级纯注解开发模式,使用Java类替代配置文件,开启了Spring快速开发赛道。
Java类代替Spring核心配置文件:
//声明当前类为Spring配置类
@Configuration
//设置bean扫描路径,多个路径书写为字符串数组格式
@ComponentScan({"com.itheima.service","com.itheima.dao"})
public class SpringConfig {
}
@Configuration注解用于设定当前类为配置类
@ComponentScan注解用于设定扫描路径,此注解只能添加一次,多个数据请用数组格式
@ComponentScan({"com.itheima.service","com.itheima.dao"})
读取Spring核心配置文件初始化容器对象切换为读取Java配置类初始化容器对象
//加载配置文件初始化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
纯注解时读取Java配置类初始化容器对象
//AnnotationConfigApplicationContext加载Spring配置类初始化Spring容器 ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);



