点击蓝字“程序员考拉”欢迎关注!
Spring中Bean的配置形式有两种,基于XML文件的方式和基于注解的方式。
1.基于XML文件的方式配置Bean
?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"
bean id="address" class="com.java.spring.autowire.Address" p:city="上海" p:street="南京路"/bean
bean id="car" class="com.java.spring.autowire.Car" p:brand="Audi" p:price="500000.0000"/bean
bean id="person" class="com.java.spring.autowire.Person" p:name="Tom" autowire="byType"/bean
/beans
像上面这样,在xml文件中使用bean…/bean标签设置Bean属性。
2.基于注解的方式配置Bean
把一个Bean加上注解放到IOC容器中,首先需要了解组件扫描。组件扫描(component scanning)是指Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件。特定组件包括:
对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称。当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 context:component-scan :
context:component-scan 下可以拥有若干个 context:include-filter 和 context:exclude-filter 子节点。
2.1 base-package属性
如图,创建如下的项目目录:
分别用TestObject,UserController,UserRepositoryImpl,UserService模拟基本注解,表现层,持久层和业务层。
TestObject.java
package com.java.spring.annotation;
import org.springframework.stereotype.Component;
@Component
public class TestObject {
}
UserController.java
package com.java.spring.annotation.controller;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
public void excute(){
System.out.println("UserController's excute...");
}
}
UserService.java
package com.java.spring.annotation.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void add(){
System.out.println("UserService's add...");
}
}
UserRepository.java
package com.java.spring.annotation.repository;
public interface UserRepository {
void save();
}
UserRepositoryImpl.java
package com.java.spring.annotation.repository;
import org.springframework.stereotype.Repository;
@Repository("userRepositoryImpl")
public class UserRepositoryImpl implements UserRepository {
@Override
public void save() {
System.out.println("UserRepositoryImpl's save...");
}
}
为Bean添加注解之后还需要在 Spring 的配置文件中声明:
context:component-scan base-package="com.java.spring.annotation"/context:component-scan
base-package=”com.java.spring.annotation”意思是要扫描annotation包下的所有类。
写一个测试类Main.java:
package com.java.spring.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java.spring.annotation.controller.UserController;
import com.java.spring.annotation.repository.UserRepositoryImpl;
import com.java.spring.annotation.service.UserService;
public class Main {
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");
UserRepositoryImpl uri=(UserRepositoryImpl) ctx.getBean("userRepositoryImpl");
System.out.println(uri);
TestObject to=(TestObject) ctx.getBean("testObject");
System.out.println(to);
UserService us=(UserService) ctx.getBean("userService");
System.out.println(us);
UserController uc=(UserController) ctx.getBean("userController");
System.out.println(uc);
}
}
运行后输出:
com.java.spring.annotation.repository.UserRepositoryImpl@4671e53b
com.java.spring.annotation.TestObject@2db7a79b
com.java.spring.annotation.service.UserService@6950e31
com.java.spring.annotation.controller.UserController@b7dd107
2.2 context:include-filter子节点
子节点表示要包含的目标类。使用context:include-filter时要将use-default-filters的值设置为false,默认为true。
比如在beans-annotation.xml中进行配置:
context:component-scan base-package="com.java.spring.annotation" use-default-filters="false"
context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/
/context:component-scan
则扫描到的组件只有@Repository(“userRepositoryImpl”)注解的持久层。
运行后输出:
com.java.spring.annotation.repository.UserRepositoryImpl@e720b71
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'testObject' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at com.java.spring.annotation.Main.main(Main.java:12)
其他Bean显示未被定义。
2.3 context:exclude-filter子节点
子节点表示要排除在外的目标类,如下排除Repository类。
在beans-annotation.xml中进行配置:
context:component-scan base-package="com.java.spring.annotation"
context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/
/context:component-scan
Main.java中修改为:
public class Main {
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");
TestObject to=(TestObject) ctx.getBean("testObject");
System.out.println(to);
UserService us=(UserService) ctx.getBean("userService");
System.out.println(us);
UserController uc=(UserController) ctx.getBean("userController");
System.out.println(uc);
UserRepositoryImpl uri=(UserRepositoryImpl) ctx.getBean("userRepositoryImpl");
System.out.println(uri);
}
}
运行后输出:
com.java.spring.annotation.TestObject@757942a1
com.java.spring.annotation.service.UserService@4a87761d
com.java.spring.annotation.controller.UserController@66d1af89
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userRepositoryImpl' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at com.java.spring.annotation.Main.main(Main.java:16)
将Repository排除,则扫描不到被@Repository(“userRepositoryImpl”)注解的Bean userRepositoryImpl,显示该Bean未被定义。
3.组件装配
context:component-scan 元素还会自动注册 AutowiredAnnotationBeanPostProcessor 实例, 该实例可以自动装配具有 @Autowired 和 @Resource 、@Inject注解的属性.
3.1 使用@Autowired自动装配所有Bean
@Autowired 注解自动装配具有兼容类型的单个 Bean属性。
示例代码:使用Autowired注解
UserController.java
package com.java.spring.annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.java.spring.annotation.service.UserService;
@Controller
public class UserController {
@Autowired
private UserService userservice;
public void excute(){
System.out.println("UserController's excute...");
userservice.add();
}
}
UserService.java
package com.java.spring.annotation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.java.spring.annotation.repository.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userrepository;
public void add(){
System.out.println("UserService's add...");
userrepository.save();
}
}
UserRepositoryImpl.java
package com.java.spring.annotation.repository;
import org.springframework.stereotype.Repository;
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository {
@Override
public void save() {
System.out.println("UserRepository's save...");
}
}
在主方法中测试:
public class Main {
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");
UserController uc=(UserController) ctx.getBean("userController");
System.out.println(uc);
uc.excute();
}
主方法中调用uc.excute();指向 UserController.java 中的excute()方法,先执行System.out.println(“UserController’s excute…”);,再调用userservice.add();方法,此时需要使用Autowired注解UserService这个Bean,否则相当于UserService这个Bean未配置到IOC容器中去,出错;userservice.add();方法指向 UserService.java中的add()方法,先执行System.out.println(“UserService’s add…”);,再调用userrepository.save();方法,同理需要注解Bean,可以看到在UserRepositoryImpl.java中使用注解@Repository(“userRepository”)。
3.2 @Resource 和 @Inject
Spring 还支持 @Resource 和 @Inject 注解,这两个注解和 @Autowired 注解的功用类似。@Resource 注解要求提供一个 Bean 名称的属性,若该属性为空,则自动采用标注处的变量或方法名作为 Bean 的名称。@Inject 和 @Autowired 注解一样也是按类型匹配注入的 Bean, 但没有 reqired 属性。建议使用 @Autowired 注解。
4.泛型依赖注入
Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用。
BaseService中引用了BaseRepository,UserService为BaseService的实现类,UserRepository为BaseRepository的实现类,那么UserService和BaseService之间会自动地建立引用关系。
示例代码:
BaseService.java
package com.java.spring.generic.di;
import org.springframework.beans.factory.annotation.Autowired;
public class BaseServiceT{
@Autowired
private BaseRepository repository;
public void add(){
System.out.println("add...");
System.out.println(repository);
}
}
BaseRepository.java
package com.java.spring.generic.di;
public class BaseRepositoryT {
}
User.java
package com.java.spring.generic.di;
public class User {
public User() {
}
}
UserService.java
package com.java.spring.generic.di;
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseServiceUser {
}
UserRepository.java
package com.java.spring.generic.di;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository{
public UserRepository() {
}
}
在beans-generic-di.xml中进行配置:
context:component-scan base-package="com.java.spring.generic.di"/context:component-scan
在主方法中进行测试:
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-generic-di.xml");
UserService userService=(UserService) ctx.getBean("userService");
System.out.println(userService);
userService.add();
}
运行输出:
com.java.spring.generic.di.UserService@8e24743
add...
com.java.spring.generic.di.UserRepository@74a10858
在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的add方法。在他们的子类中,继承了这种关系。因此我们在测试方法中调用userService.add(); 也是可以成功地调用UserReponsitory中的add方法。