码迷,mamicode.com
首页 > 其他好文 > 详细

IOC零配置

时间:2018-12-09 21:07:03      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:imp   col   pack   text   ati   nconf   one   void   配置   

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零配置

标签:imp   col   pack   text   ati   nconf   one   void   配置   

原文地址:https://www.cnblogs.com/zhou-test/p/10093103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!