【Spring】注解

编程入门 行业动态 更新时间:2024-10-17 19:34:16

【Spring】<a href=https://www.elefans.com/category/jswz/34/1768912.html style=注解"/>

【Spring】注解

文章目录

  • 1. 前言
  • 2.注解开发的准备工作
  • 3. IOC相关注解
    • DI相关注解
  • 4. DI相关注解
    • 4.1 @Value
    • 4.2 @AutoWired
    • 4.3 @Qualifier
  • 5. xml配置文件相关注解
    • 5.1 @Configuration
    • 5.2 @ComponensScan
  • 6.@Bean注解
  • 7. @PropertySource

1. 前言

Spring支持使用注解代替xml配置,注解开发可以简化配置.
注解和XML配置文件的对比:

  • 注解相对于XML配置的优点主要体现在编写的简洁性和代码量的减少上。由于注解直接写在源代码中,使得代码看起来更直观和清晰。不过,这也是注解的一个缺点,即一旦需要在源代码中进行维护或修改,就必须改动源代码,并重新编译和部署。
  • 相比之下,XML配置有其独特的优势。首先,XML是集中式的元数据,不需要与代码绑定,这使得我们可以独立于源代码进行配置修改,而无需重新编译和部署。其次,使用XML可以进行灵活的配置调整,并且当需要对软件进行扩展时,利用XML可以方便地实现。此外,XML还具有较好的可读性和易懂性。

2.注解开发的准备工作

如果要使用注解开发必须要开始组件扫描,这样加了注解的类才能被扫描出来,Spring才能去解析其中的注解

如下:

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

这样Spring就能够扫描com.example包下所有的类

3. IOC相关注解

@Component @Controller @Service @Repository 这四个注解都可以加到类上

他们都可以起到类似bean标签的作用。可以把加了该注解类的对象放入Spring容器中.实际再使用时选择任意一个都可以。但是后3个注解是语义化注解。

示例:

在之前管理bean对象都是使用xml配置文件中bean标签来管理的,例如:

<bean class="com.example.entity.Student" id="student"></bean>

如今学习了注解,就可以使用注解来代替xml配置文件了

如下:

@Data
@AllArgsConstructor
@Component("student")
public class Student {private int age;private String name;public Student() {System.out.println("执行了空参构造方法");}
}

只需要添加一个注解,并加上标识就可以了. 同样可以获取到bean对象

⭐注意不要忘记加注解扫描以及确认路径是否正确

虽然说上面四个注解用法是相同的,但也不要随便用,就像变量名不能随便取一样:

  • 如果是Service类要求使用@Service。
  • 如果是Dao类要求使用@Repository
  • 如果是Controllerl类(SpringMVC中会学习到)要求使用@Controller
  • 如果是其他类可以使用@Component

DI相关注解

4. DI相关注解

DI依赖注入就是要让Spring来给Bean对象的属性进行赋值,可以使用注解来完成

4.1 @Value

主要用于String,int等可以直接赋值的属性注入。

示例1:

@Component("student")
public class Student {@Value("20")private int age;@Value("张三")private String name;public Student() {System.out.println("执行了空参构造方法");}
}


用法并不难,就不多说了

⭐注意:@Value注解并不需要setter方法,但支持SpEL表达式

示例2:

@Component("student")
public class Student {@Value("#{20+6}")private int age;@Value("张三")private String name;public Student() {System.out.println("执行了空参构造方法");}
}

4.2 @AutoWired

@Autowired用于自动装配bean。它可以应用于字段、setter方法和构造函数上。当一个类被Spring容器管理时,可以使用@Autowired注解来注入其他bean

@Value注入的都是一些简单类型的值,如果Student中有其它类的实例,要如何注入? 这时候就需要用到@AutoWired注解

示例:

@Component("student")
public class Student {@Value("#{20+6}")private int age;@Value("张三")private String name;@Autowiredprivate StudentDao studentDao;public Student() {System.out.println("执行了空参构造方法");}
}

⭐需要注意的是:当一个类被Spring容器管理时,才可以使用@Autowired注解来注入其他bean

@Repository
public class StudentDao {@Value("111")private int num;
}

接下来介绍**@AutoWired中的属性**

默认值为true.

如果required属性值为false,那么即使要被注入的类没有被Spring容器管理,也不会报错

示例:

@Component("student")
public class Student {@Value("#{20+6}")private int age;@Value("张三")private String name;@Autowired(required = false)private StudentDao studentDao;public Student() {System.out.println("执行了空参构造方法");}
}
//@Repository
public class StudentDao {@Value("111")private int num;
}

4.3 @Qualifier

如果相同类型的bean在容器中有多个时,单独使用@AutoWired就不能满足要求,这时候可以再加上
@Qualifier来指定bean的名字从容器中获取bean注入。

⭐注意:@Qualifier是不能单独使用的

5. xml配置文件相关注解

上面的注解中,虽然可以使用注解替换掉bean,但是xml配置文件还在,接下来学习的注解就可以把xml配置文件替换掉

5.1 @Configuration

标注在类上,表示当前类是一个配置类。我们可以用注解类来完全替换掉xml配置文件。
⭐注意: 如果使用配置类替换了xml配置,spring容器要使用: AnnotationConfigApplicationContext

5.2 @ComponensScan

@ComponensScan 可以用来代替context:component-scan标签来配置组件扫描,@ComponensScan中的basePackages属性用于指定需要扫描的基础包路径。

示例:

@Configuration
@ComponentScan(basePackages = "com.example")
public class ApplicationConfig {
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component("student")
public class Student {@Value("#{20+6}")private int age;@Value("张三")private String name;
}

注意这里的Spring容器类型,以及创建实例时,传递的参数是配置类的字节码文件

6.@Bean注解

@Bean可以用来代替bean标签,主要用于第三方类的注入

例如之前的jdbc的数据源,像这种对象就不能使用注解进行配置,因为这些类的源码是在jar包里的.

这时就可以用@Bean注解

@Configuration
@ComponentScan(basePackages = "com.example")
public class ApplicationConfig {@Bean("dataSource")public DataSource getDataSource(){DataSource dataSource = new MysqlDataSource();((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false;");((MysqlDataSource)dataSource).setUser("root");((MysqlDataSource)dataSource).setPassword("123456");return dataSource;}
}

此时就可以通过getBean方法传入dataSource来获取数据源对象

7. @PropertySource

可以用来代替context:property-placeholder,让Spring读取指定的properties文件。
然后可以使用@Value来获取读取到的值。

示例:

jdbc.properties文件:

jdbc.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false;
jdbc.user=root
jdbc.password=123123

配置类:

@Configuration
@ComponentScan(basePackages = "com.example")
@PropertySource("jdbc.properties")
public class ApplicationConfig {@Value("${jdbc.url}")private String url;@Value("${jdbc.user}")private String user;@Value("${jdbc.password}")private String password;@Beanpublic DataSource getDataSource(){DataSource dataSource = new MysqlDataSource();((MysqlDataSource)dataSource).setURL(url);((MysqlDataSource)dataSource).setUser(user);((MysqlDataSource)dataSource).setPassword(password);return dataSource;}
}


由上述结果可以看出properties文件中的键值对已经成功被读取到了

⭐注意: 使用@Value来获取读取到的值时,使用的是${}

更多推荐

【Spring】注解

本文发布于:2023-11-16 09:24:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616216.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注解   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!