3. SpringMVC-使用注解开发-beans

发布时间 2023-10-06 14:06:20作者: 哲_心

万能开头:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/> <!--启动注解-->
    <context:component-scan base-package="zhe.xin"/> <!--扫描这个包下的注解-->

</beans>
  1.  新加入了:用于扫描包
    <context:component-scan base-package="zhe.xin"/> <!--扫描这个包下的注解-->
  2. 添加maven的依赖包 :aop     这里因为我导入了MVC包,里面包含了aop包,若不是MVC项目需要导入此包

  3.  使用:
    1. 加入@Component就可以被扫描到,并且添加为bean了 
    2. @Value只能设置基本类型,要设置类需使用前面所学内容@Resource或者@AutoWired和@qualifier
    3. @Value等同于 : <property name="name" value="小哲"/>

       

 

总结&提示:

  1. 由@Component衍深出: (用于分包,效果与Component相同)  都是将类放到容器中
    1. @Repository (dao包)
    2. @Service  (service业务包)
    3. @Controller (Controller控制包)
  2. 这种写法仅仅适用于普通的bean,复制的bean还是用xml合适,因为xml更加清晰明了
  3. 补充:@nullable可以声明此字段可以为空
  4. @scope  声明作用域
  5. bean还是被xml管理的 , 注解只是用于注入

 

 

 

 2023-10-06  13:59:21