spring_注解开发


注解开发

注解开发定义bean

  • 使用@Component定义bean
@Component("bookDao")
public class BookDaoImpl implements BookDao {
}
@Component
public class BookServiceImpl implements BookService {
}
  • 核心配置文件中通过组件扫描加载bean
<context:component-scan base-package="com.itheima"/>
  • Spring 提供@Component 注解的三个衍生注解

    • @Controller: 用于表现层bean定义
    • @Service: 用于业务层bean定义
    • @Repository: 用于数据层bean定义
    @Repository("bookDao")
    public class BookDaoImpl implements BookDao {
    }
    @Service
    public class BookServiceImpl implements BookService {
    }

纯注解开发

  • java类代替Spring核心配置文件

    @Configuration
    @ComponentScan("com.itheima")
    public class SpringConfig {
    }
  • @Configuration注解用于设定当前类为配置类

  • @ComponentScan注解用于设定扫描路径,此注解只能添加一次,多个数据请用数组格式

    @ComponentScan({com.itheima.service","com.itheima.dao})
  • 读取Spring核心配置文件初始化容器对象切换为读取Java配置类初始化容器对象

    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

文章作者: han yue
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 han yue !
评论
  目录