spring注入bean的方式
- 方法一:基于XML的bean定义(需要提供setter方法)
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
- <bean id="student" class="test.Student">
- <property name="name" value="张三"/>
- <property name="teacher" ref="teacher"/>
- </bean>
- <bean id="teacher" class="test.Teacher">
- <property name="name" value="李四"/>
- </bean>
- </beans>
- 方法二:基于注解的bean定义(不需要提供setter方法)
Spring为此提供了四个注解,这些注解的作用与上面的XML定义bean效果一致,在于将组件交给Spring容器管理。组件的名称默认是类名(首字母变小写),也可以自己修改:
@Component:当对组件的层次难以定位的时候使用这个注解
@Controller:表示控制层的组件
@Service:表示业务逻辑层的组件
@Repository:表示数据访问层的组件
使用这些注解的时候还有一个地方需要注意,就是需要在applicationContext.xml中声明<contex:component-scan...>一项,指明Spring容器扫描组件的包目录。
- @Component("teacher")
- public class Teacher {
- @Value("李四")
- private String name;
- public String getName() {
- return name;
- }
- }
- @Component("student")
- public class Student {
- @Value("张三")
- private String name;
- @Resource
- private Teacher teacher;
- public String getName() {
- return name;
- }
- public Teacher getTeacher() {
- return teacher;
- }
- }
- <?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:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd">
- <!--扫描组件的包目录-->
- <context:component-scan base-package="test"/>
- </beans>
- 方法三:基于Java类的bean定义(需要提供setter方法)
- @Configuration
- public class BeansConfiguration {
- @Bean
- public Student student(){
- Student student=new Student();
- student.setName("张三");
- student.setTeacher(teacher());
- return student;
- }
- @Bean
- public Teacher teacher(){
- Teacher teacher=new Teacher();
- teacher.setName("李四");
- return teacher;
- }
- }