第一种方式:使用默认无参构造函数
在默认情况下:
它会根据默认无参构造函数来创建类对象。如果 bean 中没有默认无参构造函数,将会创建失败。
<bean id="accountService" class="com.gzl.service.impl.AccountServiceImpl"/>
第二种方式: 使用普通工厂中的方法创建对象
/**
* 模拟一个工厂类(该类可能是存在于jar包中的,我们无法通过修改源码的方式来提供默认构造函数)
*/
public class InstanceFactory {
public IAccountService getAccountService(){
return new AccountServiceImpl();
}
}
<bean id="instanceFactory" class="com.gzl.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
第三种方式:使用工厂中的静态方法创建对象
/**
* 模拟一个工厂类(该类可能是存在于jar包中的,我们无法通过修改源码的方式来提供默认构造函数)
*/
public class StaticFactory {
public static IAccountService getAccountService(){
return new AccountServiceImpl();
}
}
<bean id="accountService" class="com.gzl.factory.StaticFactory" factory-method="getAccountService"></bean>
第四种方式:使用@Component,@Service,@Controler,@Repository注解
这几个注解都是同样的功能,被注解的类将会被Spring 容器创建单例对象。
@Component : 侧重于通用的Bean类
@Service:标识该类用于业务逻辑
@Controler:标识该类为Spring MVC的控制器类
@Repository: 标识该类是一个实体类,只有属性和Setter,Getter
第五种方式:使用@Bean注解
用于把当前方法的返回值作为bean对象存入spring的ioc容器中
@Bean
SessionInterceptor sessionInterceptor() {
return new SessionInterceptor();
}
第六种方式:使用@Import注解
@Import只能用在类上 ,@Import通过快速导入的方式实现把实例加入spring的IOC容器中
@Import({ 类名.class , 类名.class... })
public class TestDemo {
}
对应的import的bean都将加入到spring容器中,这些在容器中bean名称是该类的全类名 ,比如com.gzl.类名