【Spring Framework】8、使用注解开发

使用注解开发

在Spring4之后,要使用注解开发,必须要保证 aop 的包导入了

image

使用注解需要导入 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"
       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:annotation-config/>

</beans>

指定要扫描的包,这个包下面的注解才会生效

<context:component-scan base-package="com.xg"/>

image

1、bean

@Controller :组件,放在类上,说明这个类被Spring 管理了,就是bean,id默认类名小写,byName

applicationContext.xml

<?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.xg"/>
    <context:annotation-config/>

</beans>

User

package com.xg.pojo;

import org.springframework.stereotype.Controller;

// 等价于    <bean id="user" class="com.xg.pojo.User"/>
@Component
public class User {
    public  String name = "遇见星光";
}

2、属性如何注入

@Value("value") :给字段赋值

package com.xg.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

@Controller
public class User {
    // 相当于 <property name="name" value="遇见星光"/>
    @Value("遇见星光")
    public String name;
}

3、衍生注解

@Component有几个衍生注解,在web开发中,会按照MVC三层架构分层!

  • dao :【@Repository】
  • service :【@Service】
  • controller : 【@Controller】

四个注解功能一样,都是将某个类注册到Spring中,装配Bean

4、自动装配注解

@Autowired 直接在属性上使用即可!也可以在Set方法上使用!

使用 @Qualifier(value="xxx") 配合 @Autowired 使用

@Nullable // 字段标记了这个注解,说明这个字段可以为null

5、作用域

在类上使用

@Scope("singleton")
@Scope("prototype")

6、小结

XMl与注解:

  • xml :更加万能,适用于任何场合!维护简单方便
  • 注解 :不是自己类不能使用,维护相对复杂!

XMl与注解的最佳实践:

  • xml 用来管理bean
  • 注解只负责属性的注入!
posted @ 2021-07-09 11:05  遇见星光  阅读(56)  评论(0编辑  收藏  举报