5.spring使用注解开发

转载:https://blog.kuangstudy.com/index.php/archives/524/

一.Spring注解开发

1.说明

  • 在spring4之后,想要使用注解形式,必须得要引入aop的包

  • 在配置文件当中,还得要引入一个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">

</beans>

2.Bean的实现@Componet

(1)配置扫描指定包下的注解

<!--指定要扫描的包-->
<context:component-scan base-package="ustc.wzh.pojo"></context:component-scan>

(2)编写类增加注解

1 //@Component相当于<bean id="user" class="ustc.wzh.pojo.User"></bean>
2 @Component
3 public class User {
4     public String name;
5 }

(3)测试

@Test
public void test(){
    ApplicationContext applicationContext =
        new ClassPathXmlApplicationContext("beans.xml");
    User user = (User) applicationContext.getBean("user");
    System.out.println(user.name);
}

3.属性注入@Value

  • 使用注解注入属性

(1)可以不提供set方法直接写在属性上

1 //@Component相当于<bean id="user" class="ustc.wzh.pojo.User"></bean>
2 @Component
3 public class User {
4 
5     //@Value("小王")相当于<property name="name" value="小王"/>
6     @Value("小王")
7     public String name;
8 }

(2)也可以提供set方法写在set方法上

//@Component相当于<bean id="user" class="ustc.wzh.pojo.User"></bean>
@Component
public class User {
    
    public String name;

    //@Value("小王")相当于<property name="name" value="小王"/>
    @Value("小王")
    public void setName(String name) {
        this.name = name;
    }
}

4.衍生注解(@Controller,@Service,@Repository)

  • 我们这些注解,就是替代了在配置文件当中配置步骤而已!更加的方便快捷!

(1)@Component三个衍生注解

  • 为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。

    • @Controller:web层

    • @Service:service层

    • @Repository:dao层

  • 写上这些注解,就相当于将这个类交给Spring管理装配了!

5.作用域@Scope

  • singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁。

  • prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收

 1 @Component
 2 @Scope("prototype")
 3 public class User {
 4 
 5     public String name;
 6 
 7     //@Value("小王")相当于<property name="name" value="小王"/>
 8     @Value("小王")
 9     public void setName(String name) {
10         this.name = name;
11     }
12 }

6.小结

  • XML与注解比较

    • XML可以适用任何场景 ,结构清晰,维护方便

    • 注解不是自己提供的类使用不了,开发简单方便

  • xml与注解整合开发 :推荐最佳实践

    • xml管理Bean

    • 注解完成属性注入

    • 使用过程中, 需要开启注解并且扫描指定包,这样注解才能生效

猜你喜欢

转载自www.cnblogs.com/zhihaospace/p/12324554.html