Spring使用注解快速开发

1. Spring注解开发

1.1 Spring原始注解

Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。

Spring原始注解主要是替代bean的配置

注解说明
@Component使用在类上用于实例化Bean
@Controller使用在web层类上用于实例化Bean
@Service使用在service层类上用于实例化Bean
@Repository使用在dao层类上用于实例化Bean
@Autowired使用在字段上用于根据类型依赖注入
@Qualifier结合@Autowired一起使用用于根据名称进行依赖注入
@Resource相当于@Autowired+@Qualifier,按照名称进行注入
@Value注入普通属性
@Scope标注Bean的作用范围
@PostConstruct使用在方法上标注该方法是Bean的初始化方法
@PreDestroy使用在方法上标注该方法是Bean的销毁方法

注意:

使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。

<!--组件扫描-->
<context:component-scan base-package="com.wange"></context:component-scan>

使用注解@Compont或@Repository标识UserDaoImpl需要Spring进行实例化.。

package com.wange.dao.impl;

import com.wange.dao.UserDao;
import org.springframework.stereotype.Repository;
//@Component("userDao")
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    public void save() {
        System.out.println("save方法正在执行");
    }
}

使用注解@Compont或@Service标识UserServiceImpl需要Spring进行实例化
使用注解@Autowired或者@Autowired和@Qulifier或者@Resource进行userDao的注入

package com.wange.service.impl;

import com.wange.dao.UserDao;
import com.wange.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

//@Component("userService")
@Service("userService")
public class UserServiceImpl implements UserService {
	/*@Autowired
    @Qualifier("userDao")*/
    @Resource(name="userDao")
    private UserDao userDao;
	@Override
	public void save() {
        userDao.save();
    }
}

使用注解@Value进行字符串的注入

package com.wange.service.impl;

import com.wange.dao.UserDao;
import com.wange.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Value("Tom")
    private String username;
	@Value("${jdbc.driver}")
    private String driver;
    @Resource(name="userDao")
    private UserDao userDao;

    public void save() {
        System.out.println(username);
        System.out.println(driver);
        userDao.save();
    }
}

使用注解@Scope标注Bean的范围

//@Scope("prototype")
@Scope("singleton")
public class UserDaoImpl implements UserDao {
   //此处省略代码
}

使用注解@PostConstruct标注初始化方法,使用@PreDestroy标注销毁方法

@PostConstruct
public void init(){
	System.out.println("初始化方法....");
}
@PreDestroy
public void destroy(){
	System.out.println("销毁方法.....");
}
package com.wange.web;

import com.wange.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
//测试
public class UserController {
    public static void main(String[] args) {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userSerivce = applicationContext.getBean(UserService.class);
        userSerivce.save();
    }
}

1.2 Spring新注解

使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:

非自定义的Bean的配置:bean
加载properties文件的配置:context:property-placeholder
组件扫描的配置:context:component-scan
引入其他文件:import

注解说明
@Configuration用于指定当前类是一个 Spring 配置类,当创建容器时会从该类上加载注解
@ComponentScan用于指定 Spring 在初始化容器时要扫描的包。作用和在 Spring 的 xml 配置文件中的 <context:component-scan base-package=“com.wange”/>一样
@Bean使用在方法上,标注将该方法的返回值存储到 Spring 容器中
@PropertySource用于加载 .properties 文件中的配置
@Import用于导入其他配置类

@Configuration
@ComponentScan
@Import

package com.wange.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@ComponentScan("com.wange")
@Import({DataSourceConfiguration.class})
public class SpringCofiguartion {
}

@PropertySource
@value
@Bean

package com.wange.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@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")//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;
    }
}

测试

package com.wange.web;

import com.wange.config.SpringCofiguartion;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class UserController {
    public static void main(String[] args) {
        ApplicationContext applicationContext =
        new AnnotationConfigApplicationContext(SpringCofiguartion.class);

        DataSource dataSource = (DataSource)applicationContext.getBean("dataSource");
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(connection);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值