5. 基于注解的Spring应用 - Bean基本注解开发

81 阅读2分钟

Spring 除了xml配置文件进行配置外, 还可以用注解方式进行配置.

Spring提供的注解有三个版本:

  • 2.0时代, Spring开始出现注解

  • 2.5时代, Spring的Bean配置可以使用注解完成

  • 3.0时代, Spring其他配置也可以使用注解完成, 进入全注解时代

基本Bean注解, 主要是使用注解的方式替代原有xml的 < bean > 标签及其标签属性的配置

<bean id="" name="" class="" scope="" lazy-init="" init-method="" destroy-method="" abstract="" autowire="" factory-bean="" factory-method="">
    <property name="" value=""></property>
    <property name="" ref=""></property>
    <property name="">
        <list>
            <ref bean=""></ref>
        </list>
    </property>
    <constructor-arg name="" value=""></constructor-arg>
</bean>

使用 @Component 注解替代< bean >标签

xml配置注解描述
< bean id="" class="">@Component被该注解标识的类, 会在指定扫描范围内被Spring加载并实例化

可以通过 @Component 注解的 value 属性指定当前 Bean 实例的 beanName ,也可以省略不写,不写的情况下为当前类名首字母小写

// 获取方式: applicationContext.getBean("userDao");
@ Component("userDao")
public class UserDaoImpl implements UserDao {}

// 获取方式: applicationContext.getBean("userDaoImpl");
@Component
public class UserDaoImpl implements UserDao {}

使用注解对需要被Spring 实例化的 Bean 进行标注,但是需要告诉 Spring 去哪找这些 Bean ,要配置组件扫描路径

<?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/"
       xsi :schemaLocation=
                    "http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring beans.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring context.xsd">
    <!-- 告知 Spring 框架去 itheima 包及其子包下去扫描使用了注解的类 -->
    <context:component-scan base-package ="com.itheima"/>
</beans>

@Component 就单纯一个 value 属性,那么 xml 配置 < bean > 时那些属性怎么进行配置呢?

Spring 是通过注解方式去配置的之前 < bean> 标签中的那些属性,例如:@Scope

<bean id="" name="" class="" scope="" lazy-init="" init-method="" destroy-method="" abstract="" autowire="" factory-bean="" factory-method=""/>

使用 @Component 注解替代 < bean> 标签

xml配置注解描述
< bean scope="">@Scope在类上或使用了@Bean标注的方法上, 标注Bean的作用范围, 取值为singleton或prototype
< bean lazy-init="">@Lazy在类上或使用了@Bean标注的方法上, 标注Bean是否延迟加载, 取值为true和false
< bean init-method="">@PostConstruct在方法上使用, 标注Bean的实例化后执行的方法
< bean destroy-method="">@PreDestroy在方法上使用, 标注Bean的销毁前执行方法

使用上述注解完成UserDaoImpl 的基本配置

@Component("userDao")
@Scope("singleton")
@Lazy(true)
public class UserDaoImpl implements UserDao{
    @PostConstruct
    public void init(){}
    
    @PreDestroy
    public void destroy(){}
}

由于JavaEE 开发是分层的,为了每层 Bean 标识的注解语义化更加明确,@Component 又衍生出如下三个注解:

@Component衍生注解描述
@Repository在Dao层类上使用
@Service在Service层类上使用
@Controller在Web层类上使用
@Repository
public class UserDaoImpl implements UserDao{}

@Service
public class UserServiceImpl implements UserService{}

@Controller
public class UserController {}