Spring新注解

x33g5p2x  于2022-06-27 转载在 Spring  
字(2.6k)|赞(0)|评价(0)|浏览(515)

Spring新注解

使用新注解替换xml文件

web包下的UserController测试下

运行结果

 Spring新注解

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

非自定义的Bean的配置:<bean>

加载properties文件的配置:context:property-placeholder

组件扫描的配置:context:component-scan

引入其他文件:<import>

spring新注解

使用新注解替换xml文件

在config包下,创建名为DataSourceConfiguration类下

package com.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.PropertyAccessException;
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;

// 加载外部properties文件<context:property-placeholder location="classpath:MyJdbc.properties"/>
@PropertySource("classpath:MyJdbc.properties")

public class DataSourceConfiguration {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.password}")
    private String password;
    @Value("${jdbc.username}")
    private String username;

    @Bean("dataSource")//Spring会将当前方法的返回值以指定名称存储到Spring容器中
    public DataSource getDateSource() throws PropertyAccessException, PropertyVetoException {
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setPassword(password);
        dataSource.setUser(username);
        return dataSource;
    }
}

在config包下创建SpringConfiguration类下

package com.config;

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

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

//标志该类是Spring的核心配置类
@Configuration

// base是基本包他会扫描其子类下的所有包<context:component-scan base-package="com"/>
@ComponentScan("com")

//在总配置中加载分配置,加载核心配置类,若有多个,则写xx.class,xxx.class....
@Import(DataSourceConfiguration.class)
public class SpringConfiguration {

}

web包下的UserController测试下

package com.web;

import com.config.SpringConfiguration;
import com.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserController {
    public static void main(String[] args) {
        //ApplicationContext app=new ClassPathXmlApplicationContext("ApplicationContext.xml");
        ApplicationContext app=new AnnotationConfigApplicationContext(SpringConfiguration.class);
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }

}

运行结果

相关文章