首页 > 其他 > 详细

IOC零配置

时间:2018-12-09 21:00:29      阅读:211      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!