Spring一般默认创建的为单例对象,那么如何设置bean的作用范围使得创建的对象为不同的地址呢,详细见下述。
一.案例分级
二.代码示例
配置类:(相关解释见上一篇相关文章)
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.itheima")
public class SpringConfig {
}
实体类:
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
import org.springframework.stereotype.Component;
@Component("bookDao")
@Scope("prototype") //设置为多例模式
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
}
执行类:
package com.itheima;
import com.itheima.config.SpringConfig;
import com.itheima.dao.BookDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App3 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
BookDao bookDao1 =ctx.getBean(BookDao.class);
BookDao bookDao2 =ctx.getBean(BookDao.class);
System.out.println(bookDao1);
System.out.println(bookDao2);
}
}
三.执行结果
单例模式执行结果:(默认为单例,即不设置scope)
多例模式执行结果:
后续将会出更多相关优质文章,关注我持续更新!!!