spring bean的实例化

梦想与她 提交于 2019-11-26 16:49:50

bean的实例化

 手动注册

    xml文件

<bean id="exampleBean" class="examples.ExampleBean"/>

<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

这样就注册了两个bean,每个bean都有一个id和很多个名字,分别通过id和name来指定,多个名字使用逗号分隔开。这种实例化bean的方式是使用构造来实例化的bean,也可以通过静态的工厂方法,或者实例化工厂bean来实例化bean,后两种比较少见具体见 https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/core.html#beans-factory-class-static-factory-method

    编程式

@Configuration
@ComponentScan(basePackages = "org.example")
public class AppConfig  {
    ...
}

在AppConfig中使用@Bean标注在需要注册的bean即可,@ComponentScan注解就是开启自动扫描的注解,basePackages告诉spring应该扫描哪些包来实例化bean。在需要实例化的bean的类型上添加@Component,@Service,@Repository或者其他可用标签

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!