1 通過配置文件的方式。
1.1 創建bean.xml文件。
1.2 <bean></bean>標籤注bean
2 通過<context:component-scan></context:component-scan>組件掃描。
2.1 在xml文件中<context:component-scan base-package="com.componentscan"></context:component-scan>
2.2 在被掃描的包中標註@Controller@Service@Repository@Component就可以被掃描到IOC容器
缺點: 只能掃描到自己新建的bean,不能掃描第三方的bean,因爲無法給第三方bean添加註解。
3 通過@Bean註解
3.1 標識@Configuration,表明配置類。
3.2 標識@Bean,通過返回值註冊到IOC容器
@Bean
public Person person() {
return new Person("gege", 789);
}
缺陷:簡單的組件可以通過無參構造器新建實例返回,然後註冊到容器,但是如果是複雜的就很麻煩。
4 通過@Import註解。
5 使用FactoryBean註冊組件。
5.1 spring中普通的bean,以上的bean都是通過某種方法導入到容器,然後容器調用bean的無參構造器,實例化bean放入容器。
5.2 通過FactoryBean.getObject()方法,返回需要註冊的組件。
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();
}