spring 基于注解管理bean @Autowired

目录结构: 

spring 基于注解管理bean @Autowired_第1张图片

代码示例:

UserContronller.java

package com.atguigu.spring6.autowired.controller;

import com.atguigu.spring6.autowired.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class UserContronller {
    //注入Service  属性注入
    @Autowired//根据类型找到对应对象,完成注入
    private UserService userService;

    public void add(){
        System.out.println("controller");
        userService.add();
    }
}

 

 UserDao.interface

package com.atguigu.spring6.autowired.dao;

public interface UserDao {
    public void add();
}

UserdaoImpl.java

package com.atguigu.spring6.autowired.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {


    @Override
    public void add() {
        System.out.println("dao");
    }
}

UserService.interface

package com.atguigu.spring6.autowired.service;

public interface UserService {
    public void add();
}

 UserServiceImpl.java

package com.atguigu.spring6.autowired.service;

import com.atguigu.spring6.autowired.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService{
//    注入dao
    @Autowired
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("service");
        userDao.add();
    }
}

bean.xml



    
    

UserTest.java

package com.atguigu.spring6.autowired;

import com.atguigu.spring6.autowired.controller.UserContronller;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        UserContronller userContronller = ac.getBean(UserContronller.class);
        userContronller.add();
    }
}

控制台输出

spring 基于注解管理bean @Autowired_第2张图片

 此时Dao包下新增UserDao接口的实现类 UserRedisImpl.java

package com.atguigu.spring6.autowired.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

@Repository
public class UserRedisImpl implements UserDao{

    @Autowired
    private UserRedisImpl userRedis;
    @Override
    public void add() {
        System.out.println("Redis dao");
    }
}

运行报错: 

解决方法

spring 基于注解管理bean @Autowired_第3张图片

 spring 基于注解管理bean @Autowired_第4张图片

你可能感兴趣的:(Javaee,spring,java,后端)