本系列文章将会带领大家进行Spring的全面学习,持续关注我,不断更新中…
一.案例分级
简单解析:配置类替代以前的配置文件,实体类提供对象,业务类中有实体类的引用对象,在业务层中实现引用类的自动装配。
二.各层代码及详细解析
配置类:(关于配置类中两个注解的解释可以参考前面文章)
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //设置为配置类
@ComponentScan("com.itheima") //在com.otheima这个包下扫描bean对象
public class SpringConfig {
}
实体类BookDaoImpl:
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
@Repository //注解注册bean
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
}
实体接口BookDao:
package com.itheima.dao;
public interface BookDao {
public void save();
}
业务类BookServiceImol:
package com.itheima.service.impl;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookServiceImol implements BookService {
@Autowired
private BookDao bookDao;
public void save() {
System.out.println("book service save....");
bookDao.save();
}
}
@Service:注册bean对象,在执行类中使用getBean()方法获取.
@Autowired:进行自动装配,如果没有此句话,将会出现以下错误运行结果:
业务接口BookService:
package com.itheima.service;
public interface BookService {
public void save();
}
执行类App3:
package com.itheima;
import com.itheima.config.SpringConfig;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.awt.print.Book;
public class App3 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
BookService service=ctx.getBean(BookService.class);
service.save();
}
}
三.自动装配成功正确执行结果
后续文章:使用注解进行简单类型的自动装配,关注我持续更新,麻烦点个赞啦!!!