国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home 類庫下載 java類庫 Build an SSH framework more elegantly (using java configuration)

Build an SSH framework more elegantly (using java configuration)

Oct 10, 2016 am 09:04 AM

時(shí)代在不斷進(jìn)步,大量基于xml的配置所帶來的弊端也顯而易見,在XML配置和直接注解式配置之外還有一種有趣的選擇方式-JavaConfig,它是在Spring 3.0開始從一個(gè)獨(dú)立的項(xiàng)目并入到Spring中的。它結(jié)合了XML的解耦和JAVA編譯時(shí)檢查的優(yōu)點(diǎn)。JavaConfig可以看成一個(gè)XML文件,只不過是使用Java編寫的?,F(xiàn)在下面為大家展示如何編寫基于java Config 配置 spring+springmvc+hibernate。

  項(xiàng)目是在intellj IDE 下創(chuàng)建的maven項(xiàng)目,目錄如下

Build an SSH framework more elegantly (using java configuration)

按照傳統(tǒng)的方式,像DispatchServlet這樣的Servlet會(huì)配置在web.xml文件中,但是借助Servlet3規(guī)范和Spring3.1增強(qiáng),我們可以使用java將DispatchServlet配置在Servlet容器中,下面展示初始化類文件

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    //指定配置類
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { WebConfig.class };
    }
    
    //將DispatchServlet映射到“/”
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

   

}

創(chuàng)建WebInitializer需要繼承AbstractAnnotationConfigDispatcherServletInitializer,因?yàn)槔^承該類的任意類都會(huì)自動(dòng)地配置DispatchServlet和Spring應(yīng)用上下文,Spring的應(yīng)用上下文會(huì)位于應(yīng)用程序的Servlet上下文之中。

Build an SSH framework more elegantly (using java configuration)

我們可以看到底層的AbstractAnnotationConfigDispatcherServletInitializer拓展和實(shí)現(xiàn)了WebApplicationInitializer,在Servlet3 環(huán)境中,容器會(huì)在類路徑中查找實(shí)現(xiàn)了javax.servlet.ServletContainerInitializer接口的類,并將該類來配置Servlet容器,而spring提供了這個(gè)接口的實(shí)現(xiàn),名為SpringServletContainerInitializer,這個(gè)類反過來又會(huì)查找實(shí)現(xiàn)了WebApplicationInitializer的類并將配置的任務(wù)交給他們來完成,所以當(dāng)我們WebInitializer拓展了AbstractAnnotationConfigDispatcherServletInitializer ,同時(shí)就實(shí)現(xiàn)了WebApplicationInitializer,因此當(dāng)部署到Servlet3.0容器中的時(shí)候,容器就會(huì)自動(dòng)發(fā)現(xiàn)他,并用它來配置Servlet上下文。

  WebInitializer中要求DispatchServlet加載應(yīng)用上下文時(shí),使用定義在WebConfig配置類中的bean。

  在使用xml配置spring的時(shí)候,必須配置spring監(jiān)聽器,也是就ContextLoaderListener,然而很多人不知道的是,ContextLoaderListener會(huì)創(chuàng)建spring web 應(yīng)用中的另一個(gè)上下文。

  我們希望DispatchServlet加載包含Web組件的bean,如控制器、視圖解析器以及處理器映射,而ContextLoaderListener要加載應(yīng)用中的其他bean,這些bean通常是驅(qū)動(dòng)應(yīng)用后端的中間層和數(shù)據(jù)層組件。

  也就是說WebConfig的類中會(huì)用來定義DispatcherServlet應(yīng)用上下文的bean,RootConfig的類中會(huì)用來配置ContextLoadListener創(chuàng)建的上下文的bean

@Configuration
@EnableWebMvc //注解驅(qū)動(dòng)springMVC 相當(dāng)于xml中的<mvc:annotation-driven>
@ComponentScan("scau.zzf.web")//啟用組件掃描
public class WebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver=
                new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }
    //配置靜態(tài)資源的處理,要求DispatchServlet對(duì)靜態(tài)資源的請(qǐng)求轉(zhuǎn)發(fā)到servlet容器中默認(rèn)的Servlet上
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}
@Configuration
@Import(HibernateConfig.class)//導(dǎo)入Hibernate配置文件
@ComponentScan(basePackages={"scau.zzf"},
        excludeFilters={
                @ComponentScan.Filter(type= FilterType.CUSTOM, value=RootConfig.WebPackage.class)
        }
)
public class RootConfig {
    //掃描除了web以外的所有包
    public static class WebPackage extends RegexPatternTypeFilter {
        public WebPackage() {
            super(Pattern.compile("scau.zzf\\.web"));
        }
    }

}

HbernateConfig 如下

@Configuration
@PropertySource(
        value={"classpath:ds/ds-jdbc.properties"},
        ignoreResourceNotFound = true)//加載在resources下的ds-jdbc.properties
public class HibernateConfig {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String jdbcURL;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    //配置sessionFactory
    @Bean
    public SessionFactory sessionFactoryBean() {
        try {
            LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
            lsfb.setDataSource(dataSource());
            //掃描實(shí)體類
            lsfb.setPackagesToScan("scau.zzf.entity");
            Properties props = new Properties();
            //設(shè)置方言 ,采用的是MySql
            props.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
            lsfb.setHibernateProperties(props);
            lsfb.afterPropertiesSet();
            SessionFactory object = lsfb.getObject();
            return object;
        } catch (IOException e) {
            return null;
        }
    }
    //配置DataSource
    @Bean
    public DataSource dataSource(){
        BasicDataSource ds=new BasicDataSource();
        ds.setDriverClassName(driverClassName);
        ds.setUrl(jdbcURL);
        ds.setUsername(username);
        ds.setPassword(password);

        return ds;
    }
  @Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
}

實(shí)體類如下

@Entity
@Table(catalog = "hibernate",name = "users")
public class User {
    @Column
    private String username;
    @Column
    private String password;
    @Column
    private String sex;
    @Column
    private String address;
    @Column
    private int enabled;

    //GeneratedValue覆蓋@id的默認(rèn)訪問策略
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
//    @GenericGenerator是在hibernate中定義的,使用hibernate內(nèi)置的各種主鍵生成粗略生成主鍵值
//    @GenericGenerator(name = "hibernate-uuid",strategy = "uuid")
//    @GeneratedValue(generator = "hibernate-uuid")
    private int id;

    public int getEnabled() {
        return enabled;
    }

    public void setEnabled(int enabled) {
        this.enabled = enabled;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

在Test的環(huán)境下進(jìn)行測(cè)試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfig.class, RootConfig.class})
@WebAppConfiguration
public class ServiceTest {

  
    @Autowired
    private UserService userService;
    @Test
    public void userServiceTest(){

        User user=userService.findUser(1);
        System.out.println(user.getUsername());
    }

}


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276