学习笔记--注解开发
在仅仅使用原始注解的时候,想要使用的时候能够找到注解,必须在applicationContext中配置组件扫描。
<context:component-scan base-package="com.xc"/>
1.Component
写在类的上方,用于实例化bean。代替的bean字段为:
<bean id="userDao" class="com.xc.dao.impl.UserDaoImpl"></bean>
2.Controller
使用在web层类上用于实例化bean,功能与1一样,只是在层级上划分更加明确。
3.Service
使用在service层类上用于实例化bean,功能与1一样,只是在层级上划分更加明确。
4.Repository
使用在dao层类上用于实例化bean,功能与1一样,只是在层级上划分更加明确。
5.Autowired
使用在字段上根据类型依赖注入
@Autowired private UserDao userDao;
如果只有autowired 系统会按照数据类型从spring容器中进行匹配,换句话说,如果有多个userDao类型的bean就无法注入。
6.Qualifies
结合@Autowired+@Qualifier,按照名称进行注入。
@Autowired
@Qualifier("userDao")
private UserDao userDao;
按照id值从容器中匹配。
7.Resource
@Resource(name = "userDao") 相当于上面2个的集成
相当于5+6
8.Value
注入普通属性
@Value("${xc.driver}")
private String driver;
如果Value里面是一个普通的字符串,那就没什么意义了,直接赋值就行。
所以我们考虑的是如何使用properties中的内容,可以使用el表达式。
这是在applicationContext.xml配置好的情况下才能找到的。
配置内容:
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation= http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd <context:property-placeholder location="classpath:jdbc.properties" />
9.Scope
在类上标记,标志这个bean的scope范围是单例还是多类。
10.PostConstruct
使用在方法上标注该方法是Bean的初始化方法。
@PostConstruct
public void init(){
System.out.println("对象的初始化方法");
}
在Bean构造后就运行。
11.PreDestory
使用在方法上标注该方法是Bean的销毁方法。
@PreDestroy
public void destory(){
System.out.println("对象的销毁方法");
}
在Bean销毁的时候运行。
12.如果使用注解的方式注入,可以不写set方法
13.仅仅使用原始注解的情况下,applicationContext依然不能省去,里面不是自定义类的注入、配置组件扫描、context命名空间仍然需要配置,所以要搭配新注解进行使用。
14.新注解
14.1 首先需要一个Spring的核心配置类
可以理解成代替applicationContext.xml
14.2 Configuration和ComponentScan
前者是对核心配置类的声明,后者替代代码段:
<context:component-scan base-package="com.xc"/>
//标志该类是Spring的核心配置类
@Configuration
@ComponentScan("com.xc")
public class SpringConfiguration {
}
14.3 Import
如果将项目中的关于新注解的代码全部写在主配置文件中,那么会显得非常的乱,所以需要模块化。
@Import({DataSourceConfiguration.class})
14.4 PropertySource
// <context:property-placeholder location="classpath:jdbc.properties" />
@PropertySource("classpath:jdbc.properties")
代替context:property配置,当注解在配置类的上方时,配置类中就可以用el表达式使用里面的变量了。
示例:
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
}
14.5 Bean
Spring会将当前方法的返回值以指定名称存储到Spring容器中
示例:
@Bean("dataSource") //Spring会将当前方法的返回值以指定名称存储到Spring容器中
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
浙公网安备 33010602011771号