Spring Bean定义的三种方式

<!--Spring容器启动配置(web.xml文件)-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

 

一、基于XML的配置

适用场景:

  • Bean实现类来自第三方类库,如:DataSource等
  • 需要命名空间配置,如:context,aop,mvc等
<beans>
<import resource=“resource1.xml” />//导入其他配置文件Bean的定义
<import resource=“resource2.xml” />

<bean id="userService" class="cn.lovepi.***.UserService" init-method="init" destory-method="destory"> </bean> <bean id="message" class="java.lang.String">   <constructor-arg index="0" value="test"></constructor-arg> </bean> </beans>

 

二、基于注解的配置

适用场景:

  • 项目中自己开发使用的类,如controller、service、dao等

步骤如下:

1. 在applicationContext.xml配置扫描包路径

<context:component-scan base-package="com.lovepi.spring"> 
  <context:include-filter type="regex" expression="com.lovepi.spring.*"/>   //包含的目标类
  <context:exclude-filter type="aspectj" expression="cn.lovepi..*Controller+"/>   //排除的目标类
</context:component-scan>

 注:<context:component-scan/> 其实已经包含了 <context:annotation-config/>的功能

 

2. 使用注解声明bean

Spring提供了四个注解,这些注解的作用与上面的XML定义bean效果一致,在于将组件交给Spring容器管理。组件的名称默认是类名(首字母变小写),可以自己修改:

  • @Component:当对组件的层次难以定位的时候使用这个注解
  • @Controller:表示控制层的组件
  • @Service:表示业务逻辑层的组件
  • @Repository:表示数据访问层的组件
@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    public int insertSelective(SysUser record){
        return sysUserMapper.insertSelective(record);
    }

}

三、基于Java类的配置

适用场景:

  • 需要通过代码控制对象创建逻辑的场景
  • 实现零配置,消除xml配置文件

步骤如下:

  1. 使用@Configuration注解需要作为配置的类,表示该类将定义Bean的元数据
  2. 使用@Bean注解相应的方法,该方法名默认就是Bean的名称,该方法返回值就是Bean的对象。
  3. AnnotationConfigApplicationContext或子类进行加载基于java类的配置
@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;  
    }  

}  

 

public class Main {  

    public static void main(String args[]){  
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeansConfiguration.class);  
        Student student = (Student) context.getBean("student");
        Teacher teacher = (Teacher) context.getBean("teacher");
        System.out.println("学生的姓名:" + student.getName() + "。老师是" + student.getTeacher().getName());  
        System.out.println("老师的姓名:" + teacher.getName());  
    }  

} 

 

 参考:https://blog.csdn.net/lzh657083979/article/details/78524489

 

posted @ 2018-06-09 22:03  时间-海  阅读(6063)  评论(0编辑  收藏  举报