通过注解来实现依赖注入,为什么要学这个呢???之前的bean的配置都在哪里呢?都放在了beans.xml这个文件里面。当项目有很多个bean需要配置的时候,假设有30张表,需要配置每个表对应的dao实现类、service实现类,会导致配置文件比较臃肿。今天通过使用注解来简化bean文件的配置。
在项目开发中,使用xml文件和注解都可以来实现依赖注入。
下面展示一些 内联代码片。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--需要注意:扫描包,来找到需要注入的Bean的包位置; base-package:基本扫描路径,去哪个包下进行扫描; --> <context:component-scan base-package="com.aaa.pojo"/> </beans>在之前的JAVA WEB项目有dao层、service层、controller层。
丁磊–》163邮箱起家–>大话西游 等游戏,养猪;
张朝阳–>搜狐老板–》养狐狸
马化腾–》腾讯老板–>养企鹅
马云–>养猫
刘强东–》养狗
实现类:
@Component public class PigImpl implements IAnimal{ //这些私有属性,任意发挥,这里不是重点; private double weight; private String color; //在方法的实现; public void run() { System.out.println("小猪在跑..."); } }Person类:注意这时候没有Qualifier
@Component public class Person { //这时候要养猪,理解一下;注入值; //自动装配的方式; //Qualifier(value="值")不是name; @Autowired private IAnimal animal; public void feed(){ animal.run(); System.out.println("开始喂养"); } @Override public String toString() { return "Person{" + "animal=" + animal + '}'; } }不管是哪种装配Bean的方式,都需要增加装配Bean的包路径。
<!--需要注意:扫描包,来找到需要注入的Bean的包位置; base-package:基本扫描路径,去哪个包下进行扫描; --> <context:component-scan base-package="com.aaa.pojo,com.aaa.dao"/>1.为什么要使用注解注入和装配;
2.掌握@Component注解,理解@Autowired 按类型装配和@Resource按name装配;
3.使用@Component注解的时候,切记要增加扫描包的配置,注解哪个Bean,就要增加哪个扫描包路径。
l.run(); System.out.println(“开始喂养”); } @Override public String toString() { return “Person{” + “animal=” + animal + ‘}’; } }
不管是哪种装配Bean的方式,都需要增加装配Bean的包路径。 ```xml <!--需要注意:扫描包,来找到需要注入的Bean的包位置; base-package:基本扫描路径,去哪个包下进行扫描; --> <context:component-scan base-package="com.aaa.pojo,com.aaa.dao"/>注意的问题:
[外链图片转存中…(img-CcHERyds-1592274645404)]
有两个IAnimal接口的实现类的时候,报错了。
[外链图片转存中…(img-QmgktRb9-1592274645407)]
[外链图片转存中…(img-YET1Q6DV-1592274645409)]
[外链图片转存中…(img-MKslce4f-1592274645414)]
总结:
1.为什么要使用注解注入和装配;
2.掌握@Component注解,理解@Autowired 按类型装配和@Resource按name装配;
3.使用@Component注解的时候,切记要增加扫描包的配置,注解哪个Bean,就要增加哪个扫描包路径。