Spring容器创建的四种方式

1. ClassPathXmlApplicationContext ClassPath类路径加载,必须是类路径

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); //beans.xml配置文件路径
IUserService user = (IUserService) context.getBean("userService");     //IUserService 是接口,userService是配置文件中的对象id
user.add(); //调用对象的add()方法

2. 文件系统路径获得配置文件

ApplicationContext context = new FileSystemXmlApplicationContext("配置文件绝对路径")
IUserService user = (IUserService) context.getBean("userService");     //IUserService 是接口,userService是配置文件中的对象id
user.add(); //调用对象的add()方法

3. 读取注解配置-AnnotationConfigApplicationContext(不需要配置文件,直接定义一个配置类)

ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);//这里的SpringConfiguration类就是被@Configuration注解过的类
IUserService user = (IUserService) context.getBean("userService");

4. 使用BeanFactory(过时)

Resource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);
IUserServiceam = (IUserService)factory.getBean("userService");

配置文件可以结合注解使用,如果需要我们自己写的类的实例对象,可以在这些类上使用@Component、@Controller、@Service、@Repository注解创建对象并放入容器,这样在配置文件中就不用再配这些对象;而如果引用其他包的类对象,则在配置文件中配置比较方便

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值