目录
- 一.案例分级
- 二.各层代码及详细解析
- 三.自动装配成功正确执行结果
本系列文章将会带领大家进行Spring的全面学习,持续关注我,不断更新中…
一.案例分级

简单解析:配置类替代以前的配置文件,实体类提供对象,业务类中有实体类的引用对象,在业务层中实现引用类的自动装配。
二.各层代码及详细解析
配置类:(关于配置类中两个注解的解释可以参考前面文章)
package com.itheima.config; import org.springframework.co开发者_Python学习ntext.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.Sco编程pe;
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:
www.devze.compackage 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 {
    publjsic void save();
}
执行类App3:
package com.itheima;
import com.itheima.config.SpringConfig;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.conte编程客栈xt.annotation.AnnotationConfigApplicationContext;
import Java.awt.print.Book;
public class App3 {
    public static void main(String[] args) {python
       AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookService service=ctx.getBean(BookService.class);
        service.save();
    }
}
三.自动装配成功正确执行结果

后续文章:使用注解进行简单类型的自动装配
到此这篇关于Spring使用注解进行引用类型的自动装配逐步分析的文章就介绍到这了,更多相关Spring自动装配内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
 
         
                                         
                                         
                                         
                                         
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论