Spring之bean管理(注解实现)

1.bean的作用范围

使用@Scope注解定义bean的作用范围是多例的还是单例的

package domain;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("animal")
@Scope("singleton")//@Scope("prototype")表示多例
public class Animal {
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2.bean的生命周期

使用@PostConstruct和@PreDestroy两个注解控制bean的生命周期

package domain;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("animal")
@Scope("singleton")
public class Animal {
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
    @PostConstruct
    public void init(){
        System.out.println("Animal init");
    }
    @PreDestroy
    public void destroy(){
        System.out.println("Animal destroy");
    }
}

你可能感兴趣的:(Spring,spring,java,后端)