Spring定义Bean的三种方式

创建Spring项目

若创建的是Java项目,向其加入Spring包;若创建的是Maven项目,添加如下依赖:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>

编写类

public class Student {

    private int id;

    private String name;

    public Student() {
    }

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

//    set、get方法
}

一、XML方式

通过spring的配置文件定义Bean,在src目录下新建spring-conf.xml文件(文件名称可自己定,也不用必须放到src下,程序编译后,保证文件在classpath下就行)

通过<bean>标签定义一个Student Bean。bean标签的scope属性指明单实例还是多实例,默认是单实例bean。

<bean scope="singleton">:单实例在容器启动完成之间就创建好对象,spring容器运行个过程中,每个bean是单实例的;

<bean scope="prototype">:多实例在容器启动不会创建对象,获取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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- student默认单实例 -->
    <bean id="student" class="com.example.entity.Student">
        <property name="id" value="10"/>
        <property name="name" value="zhangsan"/>
    </bean>

</beans>

测试:

public class MyMain {

    public static void main(String[] args) {
//        读取配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-conf.xml");
//        获得bean
        Student student = context.getBean("student", Student.class);
        System.out.println(student);
    }

}

结果:

 

二、Java注解方式

在配置文件spring-conf.xml中,添加组件扫描,如果扫描到有@Component、@Repository、@Controller、@Service等注解的类,将此类注册为Bean。这类注解默认value值为类名首字母小写。注解的value中相当于xml配置文件中Bean的id值。

@Service用于标注业务层组件

@Controller用于标注控制层组件

@Repository用于标注数据访问组件,即DAO组件

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注

<?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="com.example.entity" />

</beans>

把注解加到Student类上

@Scope("singleton"):指定为单实例;@Scope("prototype"):指定为多实例

@Component
public class Student {

    @Value(value = "20")
    private int id;

    @Value(value = "lisi")
    private String name;

    public Student() {
    }

    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

//    set、get方法
}

测试:

public class MyMain {

    public static void main(String[] args) {
//        读取配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-conf.xml");
//        获得bean
        Student student = context.getBean("student", Student.class);
        System.out.println(student);
    }

}

结果:

三、Java配置类方式

通过@Configurable注解,把一个类变成Java配置类,@Bean注解定义一个Bean,也可以通过@ComponentScan注解指定扫描包

在@Bean可加上注解@Scope("singleton"):指定为单实例;@Scope("prototype"):指定为多实例

//@ComponentScan("com.example.entity")
@Configurable
public class BeanConfig {
    
    @Bean
    //@Scope("singleton") 默认singleton
    public Student student(){
        return new Student(30, "wang");
    }
    
}

测试:

public class MyMain {

    public static void main(String[] args) {
//        从java配置类得到上下文
        AbstractApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
//        获得bean
        Student student = context.getBean("student", Student.class);
        System.out.println(student);
    }

}

结果:

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值