接着前面一章讲其他配置文件不变

1.创建Service接口和实现类


package cn.smbms.service;

import cn.smbms.pojo.User;
import java.util.List;

public interface UserService {
    public List<User> findUserService(String userName);
}
package cn.smbms.service;

import cn.smbms.dao.UserMapper;
import cn.smbms.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;

//当前ServiceBean的名字
@Service("userService")
public class UserServiceImpl implements UserService {
    //Autowired自动装配,也就是自动注入。
    //Qualifier表示要使用spring容器中的哪个bean,将哪个bean注入到当前bean中
    @Autowired
    @Qualifier("userMapper")
    private UserMapper userMapper;
    public UserMapper getUserMapper() {
        return userMapper;
    }

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public List<User> findUserService(String userName) {
        return userMapper.getUserListByName(userName);
    }
}

2.编写配置文件,其他配置文件不变添加以下bean

<!-- 通过扫描注解标签进行service注入, base-package需要扫描类所在的包-->
<context:component-scan base-package="cn.smbms.service"></context:component-scan>

3.编写测试

@Test
    public void ts2(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        UserService us=(UserService)ctx.getBean("userService");
        List<User> userList=us.findUserService("李");
        for (User user : userList) {
            System.out.println(user.getId()+"."+user.getUserName());
        }
    }


运行结果如下:

总结:注解标签有以下几个

@service 设置bean的id

@Autowired 自动装配,自动赋值

@Qualifier("userMapper") 将哪个bean装配到当前属性中

标签: spring

添加新评论