springboot复制bean_springboot加载bean

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;

//}

}

作者公众号

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值