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或者其他可用标签