赞
踩
我们来回顾一下:
● 第一:注解怎么定义,注解中的属性怎么定义?
● 第二:注解怎么使用?
● 第三:通过反射机制怎么读取注解?
定义注解
package com.powernode.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = {ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Component {
String value();
}
以上是自定义了一个注解:Component
该注解上面修饰的注解包括:Target注解和Retention注解,这两个注解被称为元注解。
Target注解用来设置Component注解可以出现的位置,以上代表表示Component注解只能用在类和接口上。
Retention注解用来设置Component注解的保持性策略,以上代表Component注解可以被反射机制读取。
String value(); 是Component注解中的一个属性。该属性类型String,属性名是value。
使用注解
用法简单,语法格式:@注解类型名(属性名=属性值, 属性名=属性值, 属性名=属性值…)
userBean为什么使用双引号括起来,因为value属性是String类型,字符串。
另外如果属性名是value,则在使用的时候可以省略属性名,例如:
package com.powernode.bean;
import com.powernode.annotation.Component;
//@Component(value = "userBean")
@Component("userBean")
public class User {
}
读取注解
package com.powernode.test;
import com.powernode.annotation.Component;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) throws Exception {
// 存放Bean的Map集合。key存储beanId。value存储Bean。
Map<String,Object> beanMap = new HashMap<>();
String packageName = "com.powernode.bean";
String path = packageName.replaceAll("\\.", "/");
URL url = ClassLoader.getSystemClassLoader().getResource(path);
File file = new File(url.getPath());
File[] files = file.listFiles();
Arrays.stream(files).forEach(f -> {
String className = packageName + "." + f.getName().split("\\.")[0];
try {
Class<?> clazz = Class.forName(className);
if (clazz.isAnnotationPresent(Component.class)) {
Component component = clazz.getAnnotation(Component.class);
String beanId = component.value();
Object bean = clazz.newInstance();
beanMap.put(beanId, bean);
}
} catch (Exception e) {
e.printStackTrace();
}
});
System.out.println(beanMap);
}
}
负责声明Bean的注解,常见的包括四个:
● @Component
● @Controller
● @Service
● @Repository
其实都可以写成@Component,但是为了可读性 又多了以下三个,分别表示控制层、业务层、d持久层。
他们都是只有一个value属性。value属性用来指定bean的id,也就是bean的名字。
①我们要添加aop依赖,但是我们可以看到当加入spring-context依赖之后,会关联加入aop的依赖。所以这一步不用做。
②在xml文件添加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>
③在配置文件中指明要扫描的包
<?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.cky.bean"></context:component-scan>
</beans>
④在对象上使用bean注解。
package com.cky.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
//@Component(value="product")
public class Product {
private String name;
private int age;
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
注意:如果把value属性彻底去掉,spring会被Bean自动取名吗?会的。并且默认名字的规律是:Bean类名首字母小写即可。
测试类
@Test
public void test3(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring_1.xml");
Product product = applicationContext.getBean("product", Product.class);
System.out.println(product);
}
我们可以看到在spring容器中存在该bean对象。
多个包的情况下
如果是多个包怎么办?有两种解决方案:
● 第一种:在配置文件中指定多个包,用逗号隔开。
● 第二种:指定多个包的共同父包。
<!--第一种是采用英文逗号分隔开-->
<context:component-scan base-package="com.cky.bean,com.cky.annotations"></context:component-scan>
<!--第二种是指定这几个包的共同父包-->
<context:component-scan base-package="com.cky"></context:component-scan>
如果我们只想让其中的几个注解生效,比如想让@Service生效,其他不生效。
为了方便,只写到一个类里
package com.cky.bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Component
public class A {
public A() {
System.out.println("A的无参数构造方法执行");
}
}
@Controller
class B {
public B() {
System.out.println("B的无参数构造方法执行");
}
}
@Service
class C {
public C() {
System.out.println("C的无参数构造方法执行");
}
}
@Repository
class D {
public D() {
System.out.println("D的无参数构造方法执行");
}
}
@Controller
class E {
public E() {
System.out.println("E的无参数构造方法执行");
}
}
@Controller
class F {
public F() {
System.out.println("F的无参数构造方法执行");
}
}
第一种方式:
<?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.cky.bean" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
</beans>
注意
use-default-filters=“false” 表示:不再spring默认实例化规则,即使有Component、Controller、Service、Repository这些注解标注,也不再实例化。
<context:include-filter type=“annotation” expression=“org.springframework.stereotype.Service”/> 表示只有Service进行实例化。
第二种方式
:
<?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.cky.bean" use-default-filters="true">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
use-default-filters=“true” 表示:使用spring默认的规则,只要有Component、Controller、Service、Repository中的任意一个注解标注,则进行实例化。
<context:exclude-filter type=“annotation” expression=“org.springframework.stereotype.Service”/>
<context:exclude-filter type=“annotation” expression=“org.springframework.stereotype.Repository”/>表示除了Repository和Service都进行实例化。
@Component @Controller @Service @Repository 这四个注解是用来声明Bean的,声明后这些Bean将被实例化。接下来我们看一下,如何给Bean的属性赋值。给Bean属性赋值需要用到这些注解:
● @Value
● @Autowired
● @Qualifier
● @Resource
当属性的类型是简单类型时,可以使用@Value注解进行注入。
package com.cky.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Product {
@Value("cky")
private String name;
@Value("20")
private int age;
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Test
public void test3(){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring_1.xml");
Product product = applicationContext.getBean("product", Product.class);
System.out.println(product);
}
可以看到,我们并没有给属性编写setter方法,但是仍然可以注入成功。
同时,该注解也可以用在set方法 、构造参数上
package com.cky.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Product {
private String name;
private int age;
@Value("cky")
public void setName(String name) {
this.name = name;
}
@Value("20")
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.cky.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Product {
private String name;
private int age;
public Product(@Value("cky") String name, @Value("20")int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Autowired注解可以用来注入非简单类型。被翻译为:自动连线的,或者自动装配。
单独使用@Autowired注解,默认根据类型装配。【默认是byType】
看一下它的源码:
package org.springframework.beans.factory.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
源码中有两处需要注意:
● 第一处:该注解可以标注在哪里?
○ 构造方法上
○ 方法上
○ 形参上
○ 属性上
○ 注解上
● 第二处:该注解有一个required属性,默认值是true,表示在注入的时候要求被注入的Bean必须是存在的,如果不存在则报错。如果required属性设置为false,表示注入的Bean存在或者不存在都没关系,存在的话就注入,不存在的话,也不报错。
package com.cky.dao;
public interface UserDao {
public void insert();
}
package com.cky.dao.impl;
import com.cky.dao.UserDao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoforMysql implements UserDao {
@Override
public void insert() {
System.out.println("正在保存用户信息...");
}
}
属性上
package com.cky.service;
import com.cky.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Userservice {
@Autowired
private UserDao userDao;
public void save(){
userDao.insert();
}
}
构造方法上
package com.cky.service;
import com.cky.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Userservice {
private UserDao userDao;
@Autowired
public Userservice(UserDao userDao) {
this.userDao = userDao;
}
public void save(){
userDao.insert();
}
}
形参上
package com.cky.service;
import com.cky.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Userservice {
private UserDao userDao;
public Userservice(@Autowired UserDao userDao) {
this.userDao = userDao;
}
public void save(){
userDao.insert();
}
}
方法上
package com.cky.service;
import com.cky.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Userservice {
private UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void save(){
userDao.insert();
}
}
当带有参数的构造方法只有一个时,@Autowired可以省略
package com.cky.service;
import com.cky.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class Userservice {
private UserDao userDao;
public Userservice(UserDao userDao) {
this.userDao = userDao;
}
public void save(){
userDao.insert();
}
}
此时如果多了一个无参构造,就会出错。
注解上
这用来解决我们的接口被多个类实现的问题
,比如userdao接口,被两个类实现,那么我们通过类型自动注入时,就会报错,因为不知道该使用哪个类来注入,此时需要@Autowired注解和@Qualifier注解联合起来才可以根据名称进行装配,在@Qualifier注解中指定Bean名称。
package com.cky.service;
import com.cky.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class Userservice {
@Autowired
@Qualifier(value = "userDaoforOracle")
private UserDao userDao;
public void save(){
userDao.insert();
}
}
总结:
● @Autowired注解可以出现在:属性上、构造方法上、构造方法的参数上、setter方法上。
● 当带参数的构造方法只有一个,@Autowired注解可以省略。
● @Autowired注解默认根据类型注入。如果要根据名称注入的话,需要配合@Qualifier注解一起使用。
该注解不是spring内置的,是java内置的。
@Resource注解也可以完成非简单类型注入。那它和@Autowired注解有什么区别?
● @Resource注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性。(JSR-250标准中制定的注解类型。JSR是Java规范提案。)
● @Autowired注解是Spring框架自己的。
● @Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配。
● @Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用。
● @Resource注解用在属性上、setter方法上。
● @Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上。
@Resource注解属于JDK扩展包,所以不在JDK当中,需要额外引入以下依赖:【如果是JDK8的话不需要额外引入依赖。高于JDK11或低于JDK8需要引入以下依赖。】
spring6+
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.1.1</version>
</dependency>
spring5-
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
一定要注意:如果你用Spring6,要知道Spring6不再支持JavaEE,它支持的是JakartaEE9。(Oracle把JavaEE贡献给Apache了,Apache把JavaEE的名字改成JakartaEE了,大家之前所接触的所有的 javax.* 包名统一修改为 jakarta.*包名了。)
总结
@Resource注解:默认byName注入,没有指定name时把属性名当做name,根据name找不到时,才会byType注入。byType注入时,某种类型的Bean只能有一个。
虽然我们通过注解来注入bean以及完成依赖注入,但是我们仍然在使用xml配置文件来实现包扫描,如果我们想要实现全注解开发,可以通过一个配置类来代替xml配置文件。
package com.cky;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = {"com.cky.dao","com.cky.service"})
public class spring6Config {
}
@Test
public void test4(){
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(spring6Config.class);
Userservice userservice = annotationConfigApplicationContext.getBean("userservice", Userservice.class);
userservice.save();
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。