【Spring】11:纯注解开发

103 阅读1分钟

00:直接删掉 applicationContext.xml

<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl"/>

01:使用@Component定义bean

BookDaoImpl前加上@Component/@Component("bookDao")

//@Component定义bean
@Component("bookDao")
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ...");
    }
}

Spring 提供@Component注解的三个衍生注解:

  • @Controller:表示层的bean
  • @Service:业务层
  • @Repository:数据层,/ rɪˈpɑːzətɔːri / 数据库

几个注解的效果完全一致,方便我们知道这是哪一层的bean。

02:创建一个新的类SpringConfig,使用注解@Configuration@ComponentScan

//SpringConfig.java
@Configuration
@ComponentScan("com.itheima")
public class SpringConfig {
}

@Configuration:声明当前类为Spring配置类

@ComponentScan("com.itheima"):设置bean扫描路径,多个路径书写为字符串数组格式

@ComponentScan({"com.itheima.service", "com.itheima.dao"})

03:使用AnnotationConfigApplicationContext

public class AppForAnnotation {
    public static void main(String[] args) {
        //AnnotationConfigApplicationContext加载Spring配置类,初始化Spring容器
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        //按类型获取bean
        BookService bookService = ctx.getBean(BookService.class);
    }
}