spring加载bean
-
spring基于xml配置@ComponentScan会自动扫描带有@Component,@Service,@Repository,@Controller注解的类注册成bean并自动装配
-
当需要注册其他的bean需要配置xml,如:
<bean id="test" class="xx.xx.Test"/>
springboot加载bean
-
springboot无xml配置,会自动扫描启动类所在包及其子包中的所有带有@Component,@Service,@Repository,@Controller注解的类
-
如果类不在默认扫描的范围内,可以修改启动类注解扫描包的位置
@SpringBootApplication(scanBasePackages = {"xx.xx", "xx.zz"})
public class BeanApplication {
public static void main(String[] args) {
SpringApplication.run(BeanApplication.class, args);
}
}
- 注册其他的bean
- 无需装配的bean
//@Configuration注解声明当前类是一个配置类,相当于spring中xml的<beans>
@Configuration
public class BeanLoad {
//@Bean注解相当于spring中xml的<bean>
//当前方法返回的值会被注册成bean
//bean默认的名称是方法名
//如果需要设置自定义名称修改@Bean中name属性
@Bean(name = "t")
public Test test(){
return new Test();
}
}
- 需要装配的bean
@Configuration
public class BeanLoad {
@Bean
public Test test(){
return new Test();
}
//需要依赖其他bean,在方法参数中加入即可
@Bean
public Test1 test1(Test test){
Test1 test1 = new Test1();
test1.setTest(test);
return test1;
}
//或者在当前类使用@Autowired注解装配bean,方法参数就可以为空
//@Autowired
//private Test test;
//@Bean
//public Test1 test1(){
// Test1 test1 = new Test1();
// test1.setTest(test);
// return test1;
//}
}
作者公众号

本文介绍了Spring如何基于XML配置加载使用@Component等注解的类作为bean,并讨论了SpringBoot无XML配置时的自动扫描机制。在SpringBoot中,启动类所在包及子包内的相关注解类会被自动注册。若需更改扫描范围或注册额外bean,文章提供了相应方法。
7046

被折叠的 条评论
为什么被折叠?



