Spring3.0升级了纯注解开发,使用JAVA类替代配置文件,开启Spring快速开发赛道
一、@Configuration注解介绍
@Configuration:使用在类上,声明当前的类是一个配置类
package com.gg.config;
import org.springframework.context.annotation.Configuration;
/**
* @Author: {LZG}
* @ClassName: SpringConfig
* @Description: TODO
* @Date: 2022/4/25 18:01
**/
@Configuration
public class SpringConfig {
}
作用:替代了applicationContext.xml文件
二、@ComponentScan注解介绍
@ComponentScan:使用在声明的配置类上,表明所需要扫描的包
package com.gg.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @Author: {LZG}
* @ClassName: SpringConfig
* @Description: TODO
* @Date: 2022/4/25 18:01
**/
@Configuration
@ComponentScan("com.gg.dao")
public class SpringConfig {
}
作用:替代了applicationContext.xml文件中的
<context:component-scan base-package=""/>
三、注解定义Bean
@Component:表明一个类会作为组件类。告知Spring要为这个类创建bean。
该注解是通过类路径扫描自动装配到容器中的
package com.gg.dao.impl;
import com.gg.dao.BookDao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
/**
* @Author: {LZG}
* @ClassName: BookDaoImpl
* @Description: TODO
* @Date: 2022/4/25 18:19
**/
@Component
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save");
}
}
作用:等价于 <bean id="bookDao" class="com.gg.dao.impl.BookDaoImpl"/>
说明:@Component("bookDao")等价于xml配置文件中bean的id,
Spring提供@Component注解的三个衍生注解
@Controller:用于表现层bean定义
@Service:用于业务层bean定义
@Repository:用于数据层bean定义
四、Bean对象的获取
使用:AnnotationConfigApplicationContext
继承树关系
package com.gg;
import com.gg.config.SpringConfig;
import com.gg.dao.BookDao;
import com.gg.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Author: {LZG}
* @ClassName: App
* @Description: TODO
* @Date: 2022/4/25 18:18
**/
public class App {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
// 使用id获取
BookDao bookDao = (BookDao) context.getBean("bookDao");
System.out.println(bookDao);
// 通过类获取
BookService bookService = context.getBean(BookService.class);
System.out.println(bookService);
}
}
测试结果