太原便宜做網(wǎng)站的公司開封網(wǎng)站推廣
創(chuàng)建配置類
如題,前例使用xml文件加載bean類,然后通過每個bean的id獲取bean實例。注解@ComponentScan注解默認(rèn)就會裝配標(biāo)識了@Controller,@Service,@Repository,@Component注解的類到spring容器中,功能同xml問價加載bean類。
注解@Configuration標(biāo)注為配置類。
注解@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 { /** * 對應(yīng)的包掃描路徑 可以是單個路徑,也可以是掃描的路徑數(shù)組 * @return */ @AliasFor("basePackages") String[] value() default {}; /** * 和value一樣是對應(yīng)的包掃描路徑 可以是單個路徑,也可以是掃描的路徑數(shù)組 * @return */ @AliasFor("value") String[] basePackages() default {}; /** * 指定具體的掃描的類 * @return */ Class<?>[] basePackageClasses() default {}; /** * 對應(yīng)的bean名稱的生成器 默認(rèn)的是BeanNameGenerator