spring加载beanspring基于xml配置@ComponentScan会自动扫描带有@Component,@Service,@Repository,@Controller注解的类注册成bean并自动装配
当需要注册其他的bean需要配置xml,如:
springboot加载beanspringboot无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的
@Configuration
public class BeanLoad {
//@Bean注解相当于spring中xml的
//当前方法返回的值会被注册成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;
//}
}
作者公众号