Skip to content

Instantly share code, notes, and snippets.

@thombergs
Last active October 10, 2016 20:20
Show Gist options
  • Save thombergs/7055160 to your computer and use it in GitHub Desktop.
Save thombergs/7055160 to your computer and use it in GitHub Desktop.
Code samples pointing out different features of the Spring Framework.
@Component
public class EventConsumer implements ApplicationListener<E>{
@Override
public void onApplicationEvent(E event) {
try {
onEvent(event);
} catch (Exception e) {
...
}
}
}
ApplicationContext context = ...;
ApplicationEvent event = new ApplicationEvent(this);
context.publishEvent(event);
@Component
public class HelloService {
@Autowired
private SubService subService;
public String sayHello() {
return "Hello world!";
}
@PostConstruct
public void init(){
System.out.println("initializing...");
}
}
ApplicationContext context = ...;
System.out.println(context.getMessage("currentTime", params, Locale.ENGLISH));
System.out.println(context.getMessage("currentTime", params, Locale.GERMAN));
# logMessages_de.properties
currentTime=Das aktuelle Datum ist {0,date}
# logMessages_en.properties
currentTime=The current date is {0,date}
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="cacheSeconds" value="10"/>
<property name="basenames">
<list>
<value>exceptionMessages</value>
<value>logMessages</value>
</list>
</property>
</bean>
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:testdata.sql" />
</jdbc:embedded-database>
final SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
final Queue mockQueue = new MockQueue();
builder.bind("myQueue", mockQueue);
builder.activate();
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
HelloService helloService = context.getBean(HelloService.class);
@Aspect
@Component
public class PerformanceLoggingAspect {
@Pointcut(value = "execution(public * *(..))")
public void anyPublicMethod() {
}
@Around("anyPublicMethod()")
public Object logAction(final ProceedingJoinPoint pjp) throws Throwable {
final long start = System.currentTimeMillis();
try {
final Object result = pjp.proceed();
final long duration = System.currentTimeMillis() - start;
System.out.println(String.format("Execution of method %s took %d milliseconds.", joinPoint.getSignature().getName(),
duration));
return result;
} catch (Exception t) {
throw t;
}
}
}
@Component
public class QueueConsumer {
@Resource(mappedName = "myQueue")
private Queue queue;
}
@Component
public class HelloService {
@Scheduled(fixedDelay=10000, initialDelay=1000)
public void sayHello() {
System.out.println("Hello world!");
}
}
<filter>
<filter-name>securityFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>securityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:annotation-config />
<context:component-scan base-package="de.adesso.spring"/>
</beans>
<jpa:repositories base-package="de.adesso.spring"
transaction-manager-ref="transactionManager"
factory-class="de.adesso.spring.BaseRepositoryFactoryBean"
entity-manager-factory-ref="entityManagerFactory"/>
<bean id="abstractScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" abstract="true">
<property name="schedulerName" value="clusteredScheduler" />
<property name="triggers">
<list>
<ref bean="jobTrigger"/>
</list>
</property>
<property name="quartzProperties">
<props>
<!-- diverse Quartz-Properties... -->
<prop key="org.quartz.jobStore.isClustered">true</prop>
</props>
</property>
</bean>
<bean id="jobTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="helloService" />
<property name="repeatInterval" value="10000" startDelay="2000"/>
</bean>
<global-method-security pre-post-annotations="enabled" secured-annotations="enabled" />
<http use-expressions="true" create-session="never" auto-config="true">
<remember-me />
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('user')" />
<form-login login-page="/login" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="administrator, user" />
<user name="user" password="user" authorities="user" />
</user-service>
</authentication-provider>
</authentication-manager>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="java:/TransactionManager"/>
</bean>
public interface UserRepository extends JpaSpecificationExecutor<User> {
List<User> findByLastNameAndBirthYear(@Param("lastName") String lastName, @Param("birthYear") int birthYear);
@Query("SELECT COUNT(u) from User u WHERE u.birthYear = :birthYear")
Long countByBirthYear(@Param("birthYear") int birthYear);
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-config.xml"})
public abstract class UserRepositoryTest {
@Autowired
private UserRepository repository;
@Test
public void testCountByBirthYear(){
long count = repository.countByBirthYear(1982);
Assert.assertEquals(1, count);
}
}
<bean id="subService" class="de.adesso.spring.SubService"/>
<bean id="helloService" class="de.adesso.spring.HelloService">
<property name="subService" ref="subService"/>
</bean>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment