首页 > 其他分享 >Spring(十一):使用注解开发

Spring(十一):使用注解开发

时间:2022-09-26 15:01:12浏览次数:38  
标签:xml 十一 name Spring class user 注解 public

一、导包(添加依赖)

在Spring4之后,想要使用注解就必须要导入spring-aop这个包,这里我直接添加的spring-webmvc,其中包含了我们需要的包。

maven:spring-webmvc

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.23</version>
        </dependency>    

 二、在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
        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="com.jms"/>

</beans>

三、Bean的注入

package com.jms.pojo;

import org.springframework.stereotype.Component;

//等价于<bean id="user" class="com.jms.pojo.User"/>
@Component(value = "user")
public class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

使用@Component注解,value是相当于id,可以不设置,这里默认是user。

测试一下:

@Test
    public void test1() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = applicationContext.getBean("user", User.class);
        System.out.println(user.getName());
    }

 

 

 四、属性值的注入

 //等价于<property name="name" value="jms"/>
    @Value("jms")
    private String name;

使用@Value("")注解,这个注解也可以用在set方法。

测试如下:

五、作用域的注入

@Scope("singleton")
public class User {}

六、衍生的注解

@Component有几个衍生的注解,分别用于不同的分层中。

dao层:

@Repository
public class UserDao {}

service层:

@Service
public class UserService {}

Contorller层:

@Controller
public class UserController {}

这四个注解功能相同,都是将类注册到Spring容器中。

七、小结

xml与注解各有千秋,xml更加万能,适用于任何场合,维护起来更加方便;注解在简单的使用中要比xml更加简便,但复杂的配置还是xml更合适。

xml和注解的最佳实践:xml用来管理Bean,注解只负责属性的注入。

 

标签:xml,十一,name,Spring,class,user,注解,public
From: https://www.cnblogs.com/jmsstudy/p/16730159.html

相关文章