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方法");
}
}
原文地址:https://blog.csdn.net/m0_73576495/article/details/142583733
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!