spring基于注解的IOC配置

pom.xml



    4.0.0

    com.by
    Spring_IOC_Annotation
    1.0-SNAPSHOT

    
        
        
            org.springframework
            spring-context
            5.1.8.RELEASE
        
    

applicationContext.xml




    
    

dao

@Repository
public class UserDaoImpl implements UserDao {

    @Override
    public void addUser(){
        System.out.println("insert into tb_user......");
    }
}

service

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public void addUser() {
        userDao.addUser();
    }
}

测试

public class Client {
    public static void main(String[] args) {
        ApplicationContext ac = 
            new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = ac.getBean("userServiceImpl",UserService.class);
        userService.addUser();
    }
}

常见注解方式

 IOC:
            @Controller:用于web
            @Service:用于service
            @Repository:用于dao
            @Component:三层架构之外
        DI:
            //@Resource:按名称并注入
            @Autowired:按类型注入
            @Value:注入基本类型和String

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