Spring学习笔记,完全注解开发

首先我们创建一个dao包,包中包含UserDao接口和它的实现类UserDaoImpl,并利用注解@Repository创建好该类的bean管理对象

package com.Spring5.dao;

public interface UserDao {
    public void update();
}

package com.Spring5.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao{
    @Override
    public void update() {
        System.out.println("put ... ... ... ...");
    }
}

然后创建一个service包,包中创建UserService类,并利用@Service创建该类的bean管理对象,且用@Autowired装配UserDao属性

package com.Spring5.service;

import com.Spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {
    @Resource(name = "userDaoImpl")
    private UserDao userDao;
    public void add(){
        System.out.println("add ..... ...");
        userDao.update();
    }
}

创建配置类

package com.Spring5.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //作为配置类
@ComponentScan(basePackages = "com.Spring5")
public class SpringConfig {

}

@Configuration 用来使类作为配置类,@ComponentScan(basePackages = " ")用来指定需要需要扫描注解的包

创建测试类

public class Test1 {
    @Test
    public void test2(){
        ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService=context.getBean("userService",UserService.class);
        userService.add();
    }
}

其实就是把ClassPathXmlApplicationContext变成了AnnotationConfigApplicationContext
其他的和xml开发完全一样

运行测试类,运行结果如下

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值