Spring定义bean的三种方式和自动注入

定义bean有三种方式
1、在配置文件中定义该类

<bean id="student" class="test.Student">
        <property name="name" value="张三"/>
        <property name="teacher" ref="teacher"/>
    </bean>

2、在类进行中注解
@Component:当对组件的层次难以定位的时候使用这个注解
@Controller:表示控制层的组件
@Service:表示业务逻辑层的组件
@Repository:表示数据访问层的组件
且要在配置文件中配置扫描组件

<!--扫描组件的包目录-->
    <context:component-scan base-package="test"/>

3、以注入方式定义

@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;
    }

}

转:https://blog.csdn.net/sinat_34596644/article/details/53080026 这比较详细

猜你喜欢

转载自blog.csdn.net/weixin_42861564/article/details/81585538