SSM-Spring-Spring装配Bean-通过注解装配Bean-使用@Bean装配Bean
@Component 和 @Bean 是两种使用注解来定义bean的方式。@Component只能注解到类上,不能注解到方法上。大部分的开发都要引入第三方的包,且没有源码,这时候无法使用@Component注解。
Spring给予一个注解@Bean,它可以注解到方法上,并且将方法返回的对象作为Spring的Bean存放在IOC容器中。
@Bean(name="dataSource")
public DataSource getDataSource(){
Properties props=new Properties();
props.setProperty("driver","com.mysql.jdbc.Driver");
props.setProperty("url","jdbc://localhost:3306/ssm");
props.setProperty("username","root");
props.setProperty("prssword","123456789");
DataSource dataSource = null ;
try{
dataSource=BasicDataSourceFactory.createDataSource (props) ;
}catch(Exception e){
e . printStackTrace( );
}
return dataSource;
}
上面代码中,就能配置一个Bean,当容器扫描时候,就会对其生成Bean,且使用了name属性,当使用dataSource作为其BeanName,它也可以通过@Autowired或者@Qualifier等注解注入别的Bean中