Spring注解开发

优点:简化代码

创建新项目一定要配置·maven

注解

过程 图

 

1.创建模块导入坐标

新建模块

选择路径

点击确定生成

导入坐标

<!--  导入坐标-->
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.10.RELEASE</version>
        </dependency>
    </dependencies>

2.创建dao service

有时候依赖会自动生成,要改成这个才能使用

3.创建配置类 (扫描 ,被扫描)

创建config

在config里创建一个类

写入注解

注解只能出现一次

扫描

注意,没有就检查一下依赖,

4.DI注入

package config;
/*告诉idea告诉这是一个配置文件类*/

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

@Configuration
/*扫描包路径 扫描哪些dao和service包下面哪些声明了@Component,多个包的注解要使用数组的形式*/
@ComponentScan({"dao" ,"service"})
public class SpringConfig {

5.测试 

代码

APP

import config.SpringConfig;
import dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import service.BookService;

public class APP {
    public static void main(String[] args) {
        //1.加载配置类
        AnnotationConfigApplicationContext context
                = new AnnotationConfigApplicationContext(SpringConfig.class);
        //2.获取对象
        /*BookDao bookDao = context.getBean(BookDao.class);*/
        BookService bookservice = context.getBean(BookService.class);
        //3.调用方法
   /*     bookDao.save();*/
        bookservice.addBook();
    }

}

 SpringConfrig

package config;
/*告诉idea告诉这是一个配置文件类*/

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

@Configuration
/*扫描包路径 扫描哪些dao和service包下面哪些声明了@Component,多个包的注解要使用数组的形式*/
@ComponentScan({"dao" ,"service"})
public class SpringConfig {

    }

BookServiceImpl

package service.impl;

import dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import service.BookService;

//被扫描service包下面的所有类,并将其注入到spring容器中
@Component
public class BookServiceImpl implements BookService {
    //私有属性,写入注解
    @Autowired
    private BookDao bookDao;
    @Override
    public void addBook() {
        //dao层方法调用
        bookDao.save();
        System.out.println("我是bookservice的addbook方法 ");
    }
}

 

BookDaoImpl

package dao.impl;

import dao.BookDao;
import org.springframework.stereotype.Component;

//被扫描dao包下面的所有类,并将其注入到spring容器中
@Component
public class BookDaoImpl implements BookDao {
    @Override
    public void save() {

        System.out.println("我是dao中的void方法");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值