Spring原始注解
Spring原始注解主要是代替Bean的配置 使用注解进行开发时。需要在applicationContext.xml中配置组件扫描。作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。
<!--配置组件扫描-->
<context:component-scan base-package="com.ch"/>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- <bean id="userDao" class="com.ch.test.Dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.ch.test.service.impl.UserServiceImp">
<property name="userDao" ref="userDao"></property>
</bean>-->
<!--配置组件扫描-->
<context:component-scan base-package="com.ch"/>
<context:property-placeholder location="jdbc.properties"/>
</beans>
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("save running...");
}
}
@Service("userService")
@Scope("singleton")
public class UserServiceImp implements UserService {
@Value("${jdbc.url}")
private String driver;
@Resource(name = "userDao")
private UserDao userDao;
@Override
public void save() {
System.out.println(driver);
userDao.save();
}
@PostConstruct
public void init(){
System.out.println("Service对象的初始化方法");
}
@PreDestroy
public void destroy(){
System.out.println("Service对象的销毁方法");
}
}
Spring新注解
使用原始注解不能完全替代xml配置文件,还需要使用注解替代配置如下:
- 非自定义的Bean配置;Bean
- 加载properties文件配置:context:property-placeholder
- 组件扫描配置:context:component-scan
- 引入其他文件:import
@ComponentScan("com.ch")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
@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;
@Bean("dataSource")
public DataSource getDataSource() throws Exception{
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
public static void main(String[] args) {
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = app.getBean(UserService.class);
userService.save();
}
|