spring:使用注解@Configuration、@ComponentScan创建配置类(未完待续)
创建配置类
如题,前例使用xml文件加载bean类,然后通过每个bean的id获取bean实例。注解@ComponentScan注解默认就会装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中,功能同xml问价加载bean类。
注解@Configuration标注为配置类。
注解@ComponentScan指定扫描范围
配置类
package com.annotation.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;/* ** @copyright 2003-2025* @author qiao wei* @date 2025-06-13* @version 1.0* @brief * @history name* date* brief*/
@Configuration
@ComponentScan(basePackages = {"com.annotation.thirdjar","com.annotation.dao.impl"}
)
public class ConfigForDateForamt02 {
}
扫描包com.annotation.thirdjar和com.annotation.dao.impl中所有类。
加载配置类:
public void test04() {ApplicationContext context =new AnnotationConfigApplicationContext(ConfigForDateForamt02.class);InterfaceUserService userService = (InterfaceUserService) context.getBean("getUserService0100");userService.show();}
详解注解@CompScan
注解@ComponentScan源码如下
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan { /** * 对应的包扫描路径 可以是单个路径,也可以是扫描的路径数组 * @return */ @AliasFor("basePackages") String[] value() default {}; /** * 和value一样是对应的包扫描路径 可以是单个路径,也可以是扫描的路径数组 * @return */ @AliasFor("value") String[] basePackages() default {}; /** * 指定具体的扫描的类 * @return */ Class<?>[] basePackageClasses() default {}; /** * 对应的bean名称的生成器 默认的是BeanNameGenerator