Spring关于@Bean注解

基于java容器的注解 
@Bean 标识一个用于配置和初始化一个由SpringIoc容器管理的新对象的方法,类似于XML配置文件的
可以坐在Spring的@Component注解的类中使用@Bean注解任何方法(仅仅是可以)
通常和@Bean一起使用的是@Configuration,不是@Component
例:
@Component
public class App{ 声明一个类,相当于一个配置文件
@Bean
public MyService myService(){
return new MyServiceImpl();
}
}
这个上面相当于下面




自定义Bean name
@Component
public class App{ 声明一个类,相当于一个配置文件
@Bean(name="myFoo") 指定bean的name
public Foo foo(){
return new Foo();
}
}
也支持init-method和destory-method
@Bean(initMethod="init")
@Bean(destoryMethod="cleanup")

如果使用@Bean注解,没有指定bean名称的时候,默认的bean的名字是方法的名称,上面的bean的名称是myService,如果指定了bean的名字在使用默认的方法
名作为bean的id就不行了
@Bean(name="store",initMethod="init",destoryMethod="destory")这两个方法应该在实现类里面

使用@ImportResource和@Value注解进行资源文件读取


加载properties的资源文件

使用这种方式可以把properties文件里面的key对应的value



如果使用注解
@Configuration
@ImportResource("classpath:/com/acm/jdbc.properties")
public class AppConfig{

@Value("${jdbc.url}")
private String url;

@Value("${jdbc.username}")
private String username;

@Value("${jdbc.password}")
private String password;

@Bean
public DataSource dataSource(){
return new DriverSource(url,username,password);
}
}
在config.xml中使用了 然后在类上面加载@ImportResource("classpath:/com/acm/config.xml")
$(username)会取得当前用户登录系统的用户名称,所以在配置文件中一般都加jdbc.username


@Bean 默认是单例的,可以使用@Scope指定范围
@Configuration
public class Myfdfe{

@Bean
@Scope("prototype")每次请求都创新新的bean
public FEWFW efew(){

} 采用哪种注解方式
@Scope(value="prototype" proxyMode= ScopedProxyMode.TARGET_CLASS)
}

你可能感兴趣的:(Spring)