Quick Start
Start ordinary Java applications with hasor-core; use hasor-config for annotation configuration and hasor-web for Web MVC. Add the corresponding hasor-boot modules when you need executable Fat Jars or embedded containers.
Applications require JDK 17 or later.
Adding hasor-core
The following examples use Hasor 5.2.0.
- Maven
- Gradle
<dependency>
<groupId>net.hasor</groupId>
<artifactId>hasor-core</artifactId>
<version>5.2.0</version>
</dependency>
implementation "net.hasor:hasor-core:5.2.0"
Creating a container
The minimal startup is one line:
import net.hasor.core.AppContext;
import net.hasor.core.Hasor;
AppContext appContext = Hasor.create().build();
An application can create multiple independent AppContext instances. A process usually needs only one main AppContext.
Writing a Module
The configuration entry point is net.hasor.core.Module. Use ApiBinder in loadModule to declare Beans, SPI, scopes, AOP, and other features.
import net.hasor.core.ApiBinder;
import net.hasor.core.Module;
public class AppModule implements Module {
@Override
public void loadModule(ApiBinder apiBinder) {
apiBinder.bindType(HelloService.class).toInstance(new HelloService());
}
}
Pass the Module at startup:
AppContext appContext = Hasor.create().build(new AppModule());
HelloService helloService = appContext.getInstance(HelloService.class);
A Module can install other Modules:
public class RootModule implements Module {
@Override
public void loadModule(ApiBinder apiBinder) throws Throwable {
apiBinder.installModule(new UserModule());
apiBinder.installModule(new WebFeatureModule());
}
}
Reading configuration
Hasor reads hconfig.xml from the classpath by default. Specify a different filename at startup if needed:
AppContext appContext = Hasor.create()
.mainSettingWith("my-hconfig.xml")
.build(new AppModule());
You can also set configuration values directly at startup:
AppContext appContext = Hasor.create()
.addSettings("hasor", "app.name", "demo")
.build(new AppModule());
Choosing Web or Boot
Add hasor-web for Web MVC:
<dependency>
<groupId>net.hasor</groupId>
<artifactId>hasor-web</artifactId>
<version>5.2.0</version>
</dependency>
Use a Maven or Gradle packaging plugin for an executable Fat Jar. Web applications also select an embedded container module:
<dependency>
<groupId>net.hasor</groupId>
<artifactId>hasor-boot-web-tomcat</artifactId>
<version>5.2.0</version>
</dependency>
Start Web Boot applications with WebServers.run(args, RootModule.class). See Boot Startup, Project Configuration, and Web Launcher.
Using annotation configuration
With net.hasor:hasor-config, declare objects using @Configuration and @Bean, and start the application with ApplicationBoot.run(Application.class, args). Specify the scan scope through hasor.loadPackages; the startup class package is not inferred automatically. The startup class does not have to implement Module. See Java Annotation Configuration for examples, scan rules, and Bean lifecycle.