您的位置:首页 > 编程语言 > Java开发

Spring注解+AOP+JDBC

2018-02-02 21:02 190 查看

注解

@Required

注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。

public class Student {
private Integer age;
private String name;
@Required
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Required
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}


@Autowired

自动装配:

setter方法

属性

构造函数

@Autowired(required=false)

@Autowired 注释意味着依赖是必须的,它类似于 @Required 注释,然而,你可以使用 @Autowired 的 (required=false) 选项关闭默认行为。

@Qualifier

public class Profile {
@Autowired
@Qualifier("student1") // 指定Bean ID
private Student student;
........
}


<bean id="student1" class="com.tutorialspoint.Student">
<property name="name"  value="Zara" />
<property name="age"  value="11"/>
</bean>


JSR-250 注释

[b]@PostConstruct[/b]

注释作为初始化回调函数的一个替代

@[b]PreDestroy[/b]

注释作为销毁回调函数的一个替代

@Resource

注释使用一个 ‘name’ 属性,该属性以一个 bean 名称的形式被注入,它遵循 by-name 自动连接语义。

JavaConfig

声明Bean

@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}


当 @Beans 依赖对方时,表达这种依赖性非常简单,只要有一个 bean 方法调用另一个

@Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}


从另一个配置类中加载 @Bean

配置类A:

@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}


配置类B:

@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B a() {
return new A();
}
}


上下文只加载B类:

public static void main(String[] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext(ConfigB.class);
// now both beans A and B will be available...
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}


initMethod/destroyMethod

@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "cleanup" )
public Foo foo() {
return new Foo();
}
}


@Scope

@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public Foo foo() {
return new Foo();
}
}


事件处理

Spring 的核心是 ApplicationContext,它负责管理 beans 的完整生命周期。当加载 beans 时,ApplicationContext 发布某些类型的事件。例如,当上下文启动时,ContextStartedEvent 发布,当上下文停止时,ContextStoppedEvent 发布。

通过 ApplicationEvent 类和 ApplicationListener 接口来提供在 ApplicationContext 中处理事件。如果一个 bean 实现 ApplicationListener,那么每次 ApplicationEvent 被发布到 ApplicationContext 上,那个 bean 会被通知。

序号Spring 内置事件 & 描述
1*ContextRefreshedEvent***ApplicationContext 被初始化或刷新时,该事件被发布。这也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法来发生。
2ContextStartedEvent当使用 ConfigurableApplicationContext 接口中的 start() 方法启动 ApplicationContext 时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
3ContextStoppedEvent当使用 ConfigurableApplicationContext 接口中的 stop() 方法停止 ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作。
4ContextClosedEvent当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启。
5RequestHandledEvent这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。
public class CStartEventHandler
implements ApplicationListener<ContextStartedEvent>{
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("ContextStartedEvent Received");
}
}


AOP

需要在 CLASSPATH 中使用以下 AspectJ 库文件:

aspectjrt.jar

aspectjweaver.jar

aspectj.jar

aopalliance.jar

声明切入点

<aop:config>
<aop:aspect id="myAspect" ref="aBean">
<aop:pointcut id="businessService"
expression="execution(* com.tutorialspoint.Student.getName(..))"/>
...
</aop:aspect>
</aop:config>
<bean id="aBean" class="...">
...
</bean>


定义通知

<aop:config>
<aop:aspect id="myAspect" ref="aBean">
<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
<!-- a before advice definition -->
<aop:before pointcut-ref="businessService"
method="doRequiredTask"/>
<!-- an after advice definition -->
<aop:after pointcut-ref="businessService"
method="doRequiredTask"/>


基于注解的AOP

Beans.xml中要加上这样一句话:

<aop:aspectj-autoproxy/>


@Aspect
public class Logging {
@Pointcut("execution(* com.tutorialspoint.*.*(..))")
private void selectAll(){}

@Before("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}

@After("selectAll()")
public void afterAdvice(){
System.out.println("Student profile has been setup.");
}

@AfterReturning(pointcut = "selectAll()", returning="retVal")
public void afterReturningAdvice(Object retVal){
System.out.println("Returning:" + retVal.toString() );
}

@AfterThrowing(pointcut = "selectAll()", throwing = "ex")
public void AfterThrowingAdvice(IllegalArgumentException ex){
System.out.println("There has been an exception: " + ex.toString());
}
}


JDBC框架

传统的连接数据库的方式

package com.spring.test;

import org.junit.Test;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class TestJDBCTemplate {

@Test
public void test1() {
// JDBC模板依赖于连接池来获得数据的连接,所以必须先要构造连接池
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring");
dataSource.setUsername("root");
dataSource.setPassword("123456");

// 创建JDBC模板
JdbcTemplate jdbcTemplate = new JdbcTemplate();
// 这里也可以使用构造方法
jdbcTemplate.setDataSource(dataSource);

// sql语句
String sql = "select count(*)  from user";
Long num = (long) jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(num);
}


使用模板和IoC

public class UserDao {
private JdbcTemplate jdbcTemplate;

public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public void addUser(User user) {
String sql = "insert into user (username, password) values (?, ?)";
jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
}
}


配置数据源

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/TEST"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: