spring的bean管理(注解)

注解介绍:

  1.代码里面特殊标记,使用注解可以完成功能

  2.注解写法@注解名称(属性名称=属性值)

  3.注解使用在类上面,方法上面和属性上面

  注解创建对象

spring注解开发的准备工作

  1)导入spring的基本jar包

    spring-beans-4.3.11RELEASE.jar

    spring-context-4.3.11RELEASE.jar

    spring-core-4.3.11RELEASE.jar

    spring-expression-4.3.11RELEASE.jar

  2)导入aop的jar包

    spring-aop-4.3.11RELEASE.jar

  3)创建类,创建方法

  4)创建spring的配置文件,引入约束

    beans约束

    context约束(注解)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   <!--开启注解扫描:
  (1)到包里面扫描类,方法,属性上面是否有注解
  -->
  <context:annotation-config base-package="com.yztc"></context:annotation-config>
 <!--
  扫描类属性上面的注解
  <context:annotation-config></context:annotation-config>
  -->

</beans>

  5)在类上面添加注解@Component;组件.作用在类上

    创建对象的4个注解:

      @Controller : WEB层

      @Service :业务层

      @Respository  :持久层

    这三个注解让标注类本身用途明晰spring在后续版本中会对其增强

    创建单实例还是多实例

    @Scope(value="prototype")

  6)写一个测试类

  ApplicationContext context = new ClassPathXmlApplicationContext("*.xml");  *.xml文件

  context.getBean("value的值")

 

  注解创建属性

  1)创建service类,创建dao类,在service得到dao对象

  2)在service类里面定义dao类型属性

  得到dao对象,定义dao类型属性,在dao属性上面使用注解完成对象注入

  @Autowired(value=" ") 自动注入

  name属性值写的是注解创建dao对象的value的值

  @Resource(name=" ")

 

配置文件和注解混合使用

  配置对象

  <bean id =" " class=" "></bean>

  得到dao的对象

  @Resource(name=" 上面id的名称")

 

posted @ 2017-12-16 16:24  友情天  阅读(205)  评论(0编辑  收藏  举报