Spring4 注解配置bean

Spring4 注解配置bean

特定组件包括:

  • @Component :标识一个受 Spring 管理的组件
  • @Respository :标识持久层组件
  • @Service :标识业务层组件
  • @Controller :标识表现层组件

当在组件类上使用注解之后,需要在 Spring 的配置文件中声明:< context:component-scan >

           属性:

  • base-package=“com.java.spring” // 指定 IOC 容器扫描的包
  • resource-pattern=“service/*.class” //表示只扫描service下的类,用于指定扫描资源
        子节点:
  • < context:exclude-filter type=“annotation” expression=“org.springframework.stereotype.Service”/>
    表示指定排除 org.springframework.stereotype.Service 这个组件
  • < context:include-filter type=“annotation” expression=“org.springframework.stereotype.Service”/>
    表示指定使用 org.springframework.stereotype.Service 这个组件,但需要将属性 use-default-filters=“true” 改为 false 才能生效,该属性表示使用默认的 filter 默认为值 true

使用 @Autowired 自动装配 Bean

  • @Autowired 注解自动装配类型相兼容的单个 Bean
  • 可以在 构造器、普通字段,和一切有参数的方法上使用
  • 默认情况下使用 @Autowired 注解的属性需要被Spring所管理,当Spring找不到相匹配的Bean时,会抛出异常,若要某一属性允许不被设置,可以设置 注解的 required 属性为 false 即可
    例:
@Controller
public class TestController {

    @Autowired
    private TestService testService;

    public void execute(){
        System.out.println("TestController execute...");
        testService.add();
    }
}
@Service
public class TestService {
    @Autowired()
    private TestRepository testRepository;
    
    public void add(){
        System.out.println("TestService add...");
        testRepository.save();
    }

}

@Repository("testRepository")
public  class TestRepositoryImpl implements TestRepository {
    @Autowired(required = false)
    private Test test;
    @Override
    public void save() {
        System.out.println("testReopsitory save...");
        System.out.println(test);
    }
}
// @Component
public class Test {}
public class Main {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        TestController tc = (TestController) ctx.getBean("testController");
        System.out.println(tc);
        tc.execute();
    }
}

运行结果为:

com.java.spring.controller.TestController@6d3af739
TestController execute...
TestService add...
testReopsitory save...
null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值