Spring注解开发

一、配置命名空间

<?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.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  <!-- 约束路径 -- >

    <!--配置组件扫描-->
    <context:component-scan base-package="com.finnlee" ></context:component-scan>

  <!-- Spring容器加载properties文件 -->
 <context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>
</beans>

  

二、注解(必须配置组件扫描)

@Component:使用在类上用于实例化Bean    等价于  <bean id="userDao" class="com.finnlee.daoImpl.UserDaoImpl" ></bean>

@Autowired :使用在字段上用于根据类型依赖注入  (如果不加@Qualifier)

@Qualifier: 结合@Autowired一起使用用于根据名称进行依赖注入  (按照名称注入)

等价于

<bean id="userService" class="com.finnlee.services.UserServiceImpl">
     <property name="userDao" ref="userDao" ></property>
</bean>

@Resource : 相当于@Autowired+@Qualifier,按照名称进行注入  @Resource(name = "userDao")

@Controller : 使用在web层类上用于实例化Bean  和 @Component 一样

@Service : 使用在service层类上用于实例化Bean 和 @Component 一样

@Repository : 使用在dao层类上用于实例化Bean 和 @Component 一样

@Value : 注入普通属性  可以用来获取容器中的key值

@Scope : 标注Bean的作用范围 

@PostConstruct:使用在方法上标注该方法是Bean的初始化方法  等价于 init-method

@PreDestroy : 使用在方法上标注该方法是Bean的销毁方法 等价于  destroy-method

 

新注解: 

@Configuration : 用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解 

@ComponentScan : 用于指定 Spring 在初始化容器时要扫描的包。等价于  <context:component-scan base-package="com.itheima"/>

@Bean : 使用在方法上,标注将该方法的返回值存储到 Spring 容器中 

@PropertySource  : 用于加载.properties 文件中的配置

@Import : 用于导入其他配置类

posted @ 2022-03-08 22:25  FinnYY  阅读(19)  评论(0编辑  收藏  举报