账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    Spring注解驱动报错,@Autowired
    48
    0
    The annotation @Autowired is disallowed for this location.没有导包问题,就这一处报错,从买的书籍中导入的代码,应该是能这么写的,但不知道怎么改,我弄在idea里面看看。有这种用法吗?有点怀疑了。是不是书错了,应该是我错了emmm....删除了,能正常运行,还找来找去,不知道为什么写这里,但是能正常运行。
    0
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • 火锅大帝 普通会员 1楼

      在Spring框架中,@Autowired注解用于自动注入依赖项到Spring bean中。然而,如果在Spring bean的构造方法或方法中抛出错误,那么这些错误将会在调用@Autowired注解时被抛出,从而导致Spring的自动注入失效。

      以下是一些可能导致@Autowired注解在方法抛出错误时抛出异常的常见原因:

      1. 构造方法或方法签名错误:如果构造方法或方法的签名不正确,Spring容器可能无法找到该方法需要注入的bean。例如,如果构造方法的参数列表包含非Spring bean的注入对象,那么Spring容器将抛出一个MissingBeanException。

      ```java public class MyClass { private MyOtherBean otherBean;

      public MyClass(MyOtherBean otherBean) {
          this.otherBean = otherBean;
      }
      

      } ```

      1. Bean的依赖注入顺序错误:如果Spring容器的配置文件配置了不同的注入顺序,那么在类加载时,Spring容器可能会按照这些配置顺序对bean进行自动注入。如果构造方法或方法中的@Autowired注解依赖于一个特定的bean,那么这个bean可能在类加载时已经注入,而@Autowired注解将不会被触发。

      ```java @Service public class MyService { private MyOtherBean myOtherBean;

      public MyService(MyOtherBean otherBean) {
          this.myOtherBean = otherBean;
      }
      

      } ```

      1. @Autowired注解的属性类型不匹配:如果@Autowired注解的属性类型与依赖的bean的属性类型不匹配,Spring容器将抛出一个TypeMismatchException。例如,如果依赖的bean的属性类型是List,而@Autowired注解的属性类型是Map,那么Spring容器将抛出一个TypeMismatchException。

      ```java @Autowired private List myOtherBeans;

      public void doSomething(List myOtherBeans) { // Do something with myOtherBeans } ```

      1. 线程安全问题:如果在@Autowired注解的属性上使用了Spring的AOP(面向切面编程)机制,那么在某些情况下,如果Bean的构造方法或方法线程不安全,那么在调用@Autowired注解时,Spring容器可能会抛出一个ConcurrentModificationException,因为其属性上正在被修改。

      ```java @Service public class MyService { @Autowired private MyOtherBean myOtherBean;

      public void doSomething(MyOtherBean myOtherBean) {
          // Do something with myOtherBean
          // Do something with otherBean modifying it concurrently
      }
      

      } ```

      为了避免上述问题,可以在@Autowired注解的属性上使用@Autowired注解的@Synchronized注解来保证Bean的线程安全。或者,如果可能,将@Autowired注解的属性类型改为与依赖的bean的属性类型匹配的类型,以避免TypeMismatchException。同时,也可以考虑使用setter方法的@NonNull或@Nullable注解来指定bean的非空构造函数,以避免NullPointerException。

      例如:

      ```java @Service public class MyService { private MyOtherBean myOtherBean;

      @Autowired
      @NonNull
      public MyService(@NonNull MyOtherBean otherBean) {
          this.myOtherBean = otherBean;
      }
      
      // other bean methods
      

      } ```

      在这个例子中,构造函数的参数列表只包含非空构造函数,因此在调用@Autowired注解时,Spring容器不会抛出NullPointerException。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部