springioc和aop的代码示例
时间: 2023-11-20 07:45:34 浏览: 165
Spring IOC的代码示例如下:
1. 简单示例:
```
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void saveUser(User user) {
userDao.save(user);
}
}
public interface UserDao {
void save(User user);
}
public class UserDaoImpl implements UserDao {
public void save(User user) {
// 执行保存用户的逻辑
}
}
// 在配置文件中定义Bean
<bean id="userDao" class="com.example.UserDaoImpl" />
<bean id="userService" class="com.example.UserService">
<property name="userDao" ref="userDao" />
</bean>
```
2. 带有AOP的示例:
```
public class LoggingAspect {
public void beforeAdvice() {
System.out.println("Before advice: Logging before method execution");
}
public void afterAdvice() {
System.out.println("After advice: Logging after method execution");
}
}
<bean id="userDao" class="com.example.UserDaoImpl" />
<bean id="userService" class="com.example.UserService">
<property name="userDao" ref="userDao" />
</bean>
<aop:config>
<aop:aspect ref="loggingAspect">
<aop:before method="beforeAdvice" pointcut="execution(* com.example.UserService.saveUser(..))" />
<aop:after method="afterAdvice" pointcut="execution(* com.example.UserService.saveUser(..))" />
</aop:aspect>
</aop:config>
```
阅读全文