使用@Component注解的问题
@Component的缺点:该注解只能作用于类上,对于自定的类操作很方便,但是对于引入的第三方包来说很麻烦,而且往往没有这些包的源码,这样就无法在类上添加@Component注解。
问题的解决方案:
(1)定义新的类继承jar包中的类,然后在新类上添加@Component注解。
(2)使用Spring提供的注解@Bean
下面介绍注解@Bean的使用:
@Bean的使用也很简单,@Bean可以注解在方法上,并将方法返回的对象作为Spring的bean存放到Ioc容器中。@Bean不能使用在类上
@Bean注解有四个配置项:
(1)name:字符串数组
(2)autowire:标志是否是一个引用的Bean对象,默认值为Autowire.NO
(3)initMethod:自定义初始化方法
(4)destroyMethod:自定义销毁方法
下面实现一个案例,该案例囊括@Component、@ComponentScan、@Bean等注解
在实现案例前回答一个问题,何时使用注解形式,何时使用XML配置?
杨开振那本书中推荐将自己写的类使用注解形式、将第三方包或者服务类使用xml方式
(1)我使用maven构建项目,首先配置依赖,我们所用的包共三个,分别是spring-context、junit、mysql-connector-java
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.14</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
&