IOC零配置

Posted zhou-test

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOC零配置相关的知识,希望对你有一定的参考价值。

1、创建一个配置文件

package com.longteng.config;

import com.longteng.service.Imple.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan(value = "com.longteng.service.Imple")
@Configuration
public class BeanCfg {
    @Bean
    public UserService getUserService(){
        return new UserService ();
    }
}

 

 

2. 创建一个接口IUserDao

package com.longteng.service.Imple;

public interface IUserDao {

    public String addUserName(String name);
    //public Map<String,String> getUserByName(String name);
}

 

3 创建IUserDao的实现类UserDao 

package com.longteng.service.Imple;

import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDao implements IUserDao {

    @Override
    public String addUserName(String name) {
        return name+"添加成功了";
    }
}

 

 

4 创建UserService

package com.longteng.service.Imple;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class UserService {


    @Autowired
    @Qualifier("userDao")
    private IUserDao iUserDao;
    public  String add(String name){
        return  iUserDao.addUserName (name);
    }
    
}

 

5 创建测试类

package com.longteng.lesson2;

import com.longteng.config.BeanCfg;
import com.longteng.service.Imple.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;


public class AutowiredTest {
    ApplicationContext context;
    @BeforeClass
    public void initApplication(){
        context = new AnnotationConfigApplicationContext (BeanCfg.class);
    }
    @Test
    public void test(){
        UserService userService = context.getBean ("userService", UserService.class);
        String add = userService.add ("zhou");
        Assert.assertEquals ("zhou添加成功了","zhou添加成功了","success");


    }
}

 

以上是关于IOC零配置的主要内容,如果未能解决你的问题,请参考以下文章

从零开始配置vim(27)——代码片段

IOC零配置

如何优化C ++代码的以下片段 - 卷中的零交叉

Spring学习总结——Spring实现IoC的多种方式

如何从零开始集成DTM Android SDK

从零开始实现一个简易的Java MVC框架--实现IOC