博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring_IOC
阅读量:7117 次
发布时间:2019-06-28

本文共 2996 字,大约阅读时间需要 9 分钟。

我们都知道,如果要在不同的类中使用同一个对象一般我们我们都需要在每一个类中都去new一个新的对象,也有的人会为这个对象写一个工具类,无论哪种方法都需要我们自己去创建,不但繁琐,而且相当耗损资源,所以才有了Spring使用的必要性,也就是说,Spring的众多功能中为我们创建对象就是其中之一。话不多说直接上代码:

1 /*2 *dao层接口3 */4 public interface AccountDao {5     void say();6 }
1 /*2 * dao层实现类3 */4 public class AccountDaoImpl implements AccountDao {5     @Override6     public void say() {7         System.out.println("我是dao层>>>>>>>>>>>>>");8     }9 }
/** * service层接口 */public interface AccountService {    void say();}
1 /** 2  * service实现类 3  */ 4 public class AccountServiceImpl implements AccountService { 5  6     private AccountDao dao;//创建dao层成员,并写出它的set,get方法 7  8     @Override 9     public void say() {
       dao.say();//直接调用dao层的方法10 System.out.println("我是service层>>>>>>>>>>>>>");11 }12 13 //get方法14 public AccountDao getDao() {15 return dao;16 }17 //set方法18 public void setDao(AccountDao dao) {19 this.dao = dao;20 }21 }

 

第一种纯XML方式

 

1 
2
5
6
7
8
9
11
12
13

 创建测试类

1 public class App  2 { 3     public static void main( String[] args ) 4     { 5         //spring读取xml配置文件 6         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 7         //从spring容器中获取service层的对象 8         AccountService bean = context.getBean(AccountService.class); 9         //调用service层的方法10         bean.say();11     }12 }

第一种注解方式,需要一个xml配置。接口都不变,只是在实现类上有些变化

1 /* 2 * dao层实现类 3 */ 4 @Repository("dao")//相当于xml中配置的dao层的bean节点 5 public class AccountDaoImpl implements AccountDao { 6     @Override 7     public void say() { 8         System.out.println("我是dao层>>>>>>>>>>>>>"); 9     }10 }
/** * service实现类 */@Service("service")//相当于xml层中配置的service的bean节点public class AccountServiceImpl implements AccountService {    @Autowired//默认按类型匹配    @Qualifier("dao")//与autowired连用可以按名字匹配    private AccountDao dao;//创建dao层成员,并写出它的set,get方法    @Override    public void say() {        dao.say();        System.out.println("我是service层>>>>>>>>>>>>>");    }    //get方法    public AccountDao getDao() {        return dao;    }    //set方法    public void setDao(AccountDao dao) {        this.dao = dao;    }}

 xml配置:

1 
2
6
7
8
9
10

测试类不变,自行测试

接下来最后一种就是不需要xml但是需要一个核心配置类AppConfig,取代xml

1 @Configuration//标识,代表本类为核心配置类2 @ComponentScan("com.lhf")//需要扫描的包的位置3 public class AppConfig {4     //暂时什么都不用写,后续又其他操作5 }

接口和实现类与上一种相同但是测试类略有变化

1 public class App  2 { 3     public static void main( String[] args ) 4     { 5         //spring读取核心配置类 6         ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 7         //从spring容器中获取service层的对象 8         AccountService bean = context.getBean(AccountService.class); 9         //调用service层的方法10         bean.say();11     }12 }

以上就是spring中对属性ioc对对象注入的几种方式。这里写的不全,有需要的可以查以下官方文档。

转载于:https://www.cnblogs.com/Tiandaochouqin1/p/10387213.html

你可能感兴趣的文章