spring-2-注解
Spring注解开发
原始注解
@Qulifier(“bean-id”)
注解方式注入 可以省掉set方法.
常用:
只写@Autowired : 按照数据类型从Spring容器中进行匹配的
@Autowired + @Qulifier :按照id名称 从容器中进行匹配,
@Resource(name=”bean-id”): 相当于@A.. + @Q..
@Value的作用
//从spring容器中去找键,并把她的值赋给driver.
@Value("${jdbc.driver}")
private String driver;
@PostConstruct : 构造函数之后调用的方法
@PreDestroy :销毁之前调用的方法,没有执行是因为jdbc已经执行完毕了,容器还没关闭,可手动关闭容器在程序退出前。
新注解
第三方定义的 类怎么办?比如c3p0数据源类
import注解用法
用法:
@Configuration @Configuration //配置类,里面@Bean用于方法 返回的对象放入spring容器
//
@ComponentScan //从哪扫描注解创建bean
//context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties") //读取配置文件
public class Configura {
@Value("${driver}")
private String driver;
@Bean("dataSource") //Spring会将当前方法的返回值以指定名称存储到Spring容器中
public DataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl("jdbc:mysql://localhost:3306/ustc");
dataSource.setUsername("root");
dataSource.setPassword("yyyyyyyy");
return dataSource;
}
}
用注解后:核心配置文件 得改成核心配置类。
ApplicationContext context = new AnnotationConfigApplicationContext(Configura.ApplicationContext context = new AnnotationConfigApplicationContext(Configura.class);
ContextConfiguration注解是test时用的
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!