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