系列十、IOC操作bean管理(全注解方式)

一、pom.xml


    
      org.springframework
      spring-aop
      5.2.5.RELEASE
    
    
      commons-logging
      commons-logging
      1.1.1
    
    
      com.alibaba
      druid
      1.2.16
    
    
      org.springframework
      spring-beans
      5.2.5.RELEASE
    
    
      org.springframework
      spring-context
      5.2.5.RELEASE
    
    
      org.springframework
      spring-core
      5.2.5.RELEASE
    
    
      org.springframework
      spring-expression
      5.2.5.RELEASE
    


    
      junit
      junit
      4.13.2
    
    
    
      org.projectlombok
      lombok
      1.18.22
    
    
      org.slf4j
      slf4j-api
      1.7.32
    
    
      ch.qos.logback
      logback-classic
      1.2.10
    

二、配置类

package org.star.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"org.star"})
public class MySpringConfig {

}

三、业务代码

3.1、UserDao

package org.star.dao;

public interface UserDao {

    void add();

}

3.2、UserDaoImpl

package org.star.dao.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.star.dao.UserDao;

@Slf4j
@Repository
public class UserDaoImpl implements UserDao {

    @Override
    public void add() {
        log.info("UserDaoImpl add execute...");
    }
}

3.3、UserService

package org.star.service;

public interface UserService {

    void add();

}

3.4、UserServiceImpl

package org.star.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.star.dao.UserDao;
import org.star.service.UserService;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void add() {
        log.info("UserServiceImpl add execute...");
        userDao.add();
    }
}

四、测试代码

package org.star;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.star.config.MySpringConfig;
import org.star.service.UserService;

@Slf4j
public class AppTest {

    @Test
    public void testService() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MySpringConfig.class);
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        log.info("userService:{}",userService);
        userService.add();
    }

}

你可能感兴趣的:(Spring5系列,java,开发语言)