美文网首页
@Autowired (2020-08-24)

@Autowired (2020-08-24)

作者: Iterate | 来源:发表于2020-08-24 21:06 被阅读0次

@Autowired 使用 报错空指针等

错误使用:在main中直接 调用
原因:此时bean 还未注入到spring容器中,大概生命周期的意思。还没被扫
正确使用:使用接口等 方式,访问使用

需要加以下 一个注解才能被 扫到 进入bean中

package com.example.demo3;
import org.springframework.stereotype.Service;
@Service
public class Hallo implements IHallo {
    int test1 = 123;
    static int test2 = 123;
    public List toTest;

    @Override
    public void eat() {

    }
}

@Component 最普通的组件,可以被注入到spring容器进行管理
@Repository 作用于持久层
@Service 作用于业务逻辑层
@Controller 作用于表现层(spring-mvc的注解)

总结
@Component, @Service, @Controller, @Repository是spring注解,注解后可以被spring框架所扫描并注入到spring容器来进行管理
@Component是通用注解,其他三个注解是这个注解的拓展,并且具有了特定的功能
@Repository注解在持久层中,具有将数据库操作抛出的原生异常翻译转化为spring的持久层异常的功能。
@Controller层是spring-mvc的注解,具有将请求进行转发,重定向的功能。
@Service层是业务逻辑层注解,这个注解只是标注该类处于业务逻辑层。
用这些注解对应用进行分层之后,就能将请求处理,义务逻辑处理,数据库操作处理分离出来,为代码解耦,也方便了以后项目的维护和开发。

相关文章

网友评论

      本文标题:@Autowired (2020-08-24)

      本文链接:https://www.haomeiwen.com/subject/tplojktx.html