Spring @Bean用法

1.@Bean

作用:
用于把当前方法的返回值作为bean对象存入spring的容器中
属性:
name:用于指定bean的id。当不写时,bean的id默认为当前方法的名称
细节:
当我们使用注解配置方法时,如果方法有参数,spring框架会到bean容器
中查找有没有可用的bean对象,查找的方式和Autowired注解的方式是一
样的、例如
@Configuration
@ComponentScan(basePackages="com.bookmanagesystem")
public class SpringConfiguration {
@Bean(name = "userService2")
public IUserService getService() {
return new UserServiceImpl();
} }

 自己写的配置文件

@Configuration
@ComponentScan("com.bookmanagesystem")
@Import(JdbcConfig.class)
public class SpringConfig {

	@Bean//将日期作为配置文件存到容器中去
	public Date getBirthday(@Value("")String str) {
		try {
			return new SimpleDateFormat("yyyy-MM-dd").parse("2021-11-8");
		} catch (ParseException e) {
			throw new RuntimeException("日期转换出错了!", e);
		}
	}
	
}

UserDaoimpl接口实现类

@Repository("userDao3")
public class UserDaoImpl3 implements IUserDao {

	private String name;
	private int age;
	private Date birthday;

	/*
	 * 构造方法默认采取了自动装配Autowired策略,对于参数中的引用类型,将会自动在容器中找bean来注入
	 */
	public UserDaoImpl3(@Value("wangwu")String name,@Value("20") int age, Date birthday) {
		super();
		this.name = name;
		this.age = age;
		this.birthday = birthday;
	}

	@Override
	public String queryUser() {
		// 模拟查询到一个用户
		return name + "," + age + "," + birthday;
	}

}

主函数

public static void main(String[] args) {
        // 1. 获取核心容器对象
        //ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        IUserDao serBean =  context.getBean("userdao3",IUserDao.class);
        System.out.println(serBean.queryUser());
        // 3.关闭容器(如果不记得关闭容器,最典型的问题就是数据库连接不能释放)
        //((ClassPathXmlApplicationContext) context).close();
        ((AnnotationConfigApplicationContext) context).close();
    }

总结:

应用场景
例如在使用MyBatis框架时,核心是得到SqlSession对象,就可以通过编写
方法来创建SqlSession对象,然后使用@Bean注解来注入到容器中

猜你喜欢

转载自blog.csdn.net/qq_53463161/article/details/121216863