Spring-------使用Spring创建对象

1.applicationContext.xml文件的内容:
<? xml version = "1.0" encoding = "UTF-8" ?>
< beans xmlns = "http://www.springframework.org/schema/beans"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
     xmlns:p = "http://www.springframework.org/schema/p"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-4.1.xsd" >
</ beans >
2.编写domain,DAO,service;
3.在Spring中注册组件:
要Spring框架中可以使用二种方式:1 XML  2 ANNOTATION
     < bean id ="DAO" class ="com.demo.DemoDAOImpl" />
     id 实体名称  class 类名
4.获得组件:
获得ApplicationContext的类。使用这个类可以从Spring工厂中获得对象。
public static void main(String[] args ) {
         ApplicationContext context = new ClassPathXmlApplicationContext(
"/applicationContext.xml" );
        DemoDAO demoDAO = (DemoDAO) context .getBean( "demoDAO" );
         demoDAO .save();
     }
5.实现IOC和DI:
< bean id = class = >
         < property name = ref = /> <!-- 依赖注入 -->
     </ bean >

6.使用Spring指定构造方法创建对象:
< bean id = class = >
      
<constructor-arg index="0" ref="demoDAO"/>
     </ bean >
public class DemoService{
private DemoDAO demodao;
public DemoService(){
}
public DemoService (DemoDAO demoDAO){
this.demoDAO=demoDAO;
}
}
7.使用静态工厂方法创建对象:
< bean id =demoDAO" class ="com.factory.DAOFactory" factory-method ="createDAO" />
public class DAOFactory{
public static DemoDAO createDAO(){
return new DemoDAOImpl();
}
}
8.使用实例工厂方法创建对象:
< bean id ="DAOFactory" class ="com..factory.DAOFactory" />
< bean id ="demoDAO" factory-bean ="DAOFactory" factory-method ="createDAO" />
public class DAOFactory{
public DemoDAO createDAO(){
return new DemoDAOImpl();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值